简体   繁体   English

自下而上的动态编程

[英]bottom up dynamic programming

I was trying to write a dynamic programming that counts the number of ways in which the road can be paved by using stones that are 2, 3, 5 meters. 我试图编写一个动态程序,计算使用2米,3米,5米的石头可以铺砌道路的方式。 When I put 2, it gave me an error and starting from 2 to 20, it was supposed to give an output of 当我输入2时,它给了我一个错误,并且从2到20开始,应该给出一个输出

1, 1, 1, 3, 2, 5, 6, 8, 14, 16, 27, 36, 51, 77, 103, 155, 216, 309, 448 1,1,1,3,2,5,6,8,14,16,27,36,51,77,103,155,216,309,448

My code gives this result when I start the input from 3. Did I misunderstand something here? 当我从3开始输入时,我的代码给出了此结果。是否误解了这里的内容?

def waysRoad(n):
    if n<0:
        return 0

    dp = [0] * (n+1)
    dp[0] = 1
    dp[1] = 0
    for i in range(2, n):
        sum = 0
        if i >=2:
            sum += dp[i-2]

        if i >=3:
            sum += dp[i-3]
        if i >=5:
            sum += dp[i-5]
        dp[i] = sum
    return dp[i]

To fill n-th list entry, you need to use loop limit n+1 : 要填充第n-th列表条目,您需要使用循环限制n+1

for i in range(2, n + 1):

also it is worth to change return to 也值得改变返回

return dp[n]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM