【问题标题】:recursive tree for the cutting Rod prob set切割棒概率集的递归树
【发布时间】:2016-03-12 14:54:15
【问题描述】:

我有切割棒的递归解决方案(动态问题)。问题描述为here。 如果您运行此代码,您会注意到当外部 for 循环迭代时,递归函数不会再次运行(请参阅 'i' 不会再次打印 0 和 1)。我想知道 Python 是否会记住上一次迭代的递归结果?我认为每次迭代 i 时它都必须进行递归调用,但看起来不像。

def cutRod(n, prices):
    if n <= 1:
        return prices[0]
    max_val = 0
    for i in range(n):
        print i, max_val
        max_val = max(max_val, prices[i] + cutRod(n-i-1, prices))
        print max_val
    return max_val

prices = [2,5,3]
n = len(prices)
print cutRod(n,prices)

【问题讨论】:

    标签: python memory recursion dynamic


    【解决方案1】:

    您的代码几乎是正确的,除了将第二行从if n &lt;= 1: 更改为if n == 1:,这将使max_val = max(max_val, prices[i] + cutRod(n-i-1, prices)) 行在i = n-1 时正常工作。修改后,如果i = n-1,我们有cutRod(n-i-1, prices) = cutRod(n-(n-1)-1, price)) = cutRod(0, price) = 0,而不是修改前的cutRod(0, price) = prices[0]。实际上,递归函数在您的代码中再次运行,并且可以记住上一次迭代中的max_value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 2011-11-19
      • 2021-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多