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. When I put 2, it gave me an error and starting from 2 to 20, it was supposed to give an output of
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?
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
:
for i in range(2, n + 1):
also it is worth to change return to
return dp[n]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.