目录
需求背景
给你一个数组,把这个数组里面每个数字都求差,然后把这些差都求和。
正常演示步骤:
[1,3,5]
1-3 = 2
1-5 = 4
-
3-5 = 2
sum = 8
反过来思考子问题是什么:
[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(f(n))
标签:return,递归,temp,sum,实践,reN,print,reverse
From: https://www.cnblogs.com/mysticbinary/p/18389301