目录
需求背景
给你一个数组,把这个数组里面每个元素之间都求差(结果忽略负符号),然后把这些差求和。
给你数组 n = [1,3,5]
正常演示步骤:
[1,3,5]
1-3 = 2
1-5 = 4
-
3-5 = 2
sum = 8
反过来思考子问题是什么:
假设已经有一个x函数帮忙搞定了,自己之做一步:(3-1) + x()
[1,3,5]
reverse [5,3,1]
5-3 = 2
5-1 = 4
-
3-1 = 2
sum = 8
[1,3,5,7]
reverse [7,5,3,1]
7-5 = 2
7-3 = 4
7-1 = 6
-
5-3 = 2
5-1 = 4
-
3-1 = 2
sum = 20
写出代码:
code:
def f(n) -> int:
temp = []
if len(n) == 1:
return sum(temp)
reN = list(reversed(n))
for i, x in enumerate(reN): # i[5,3,1]
if i != 0:
print("reN ", reN)
print(reN[0]," - ", reN[i])
temp.append(abs(reN[0] - reN[i]))
print(temp)
return sum(temp) + f(n[:-1])
n = [1, 3, 5, 7]
print("sum :",f(n))
out:
reN [7, 5, 3, 1]
7 - 5
[2]
reN [7, 5, 3, 1]
7 - 3
[2, 4]
reN [7, 5, 3, 1]
7 - 1
[2, 4, 6]
reN [5, 3, 1]
5 - 3
[2]
reN [5, 3, 1]
5 - 1
[2, 4]
reN [3, 1]
3 - 1
[2]
sum : 20