--- 钢条切割问题 --- 某公司出售钢条,出售价格和钢条长度之间的关系如下: 长度i 1 2 3 4 5 6 7 8 9 10 价格pi 1 5 8 9 10 17 17 20 24 30 问:现有一段长度为 n 的钢条和上面的价格表,求切割钢条方法,使总收益最大
1. 递归
def cut_rod_recursion_1(p, n):
"""最慢的递归 2 次: 大量重复计算"""
if n == 0:
return 0
else:
res = p[n]
for i in range(1, n):
res = max(res, cut_rod_recursion_1(p, i) + cut_rod_recursion_1(p, n - i))
return res
def cut_rod_recursion_2(p, n):
"""递归一次: top-down"""
if n == 0:
return 0
else:
res = 0
for i in range(1, n + 1):
res = max(res, p[i] + cut_rod_recursion_2(p, n - i))
return res