java实现楼梯式效果_Java编程:楼梯动态编程示例

小编典典

好的,这就是代码的作用。

`if (n<0)`

`return 0;`

如果没有足够的剩余步骤,则不要计算。例如,如果还剩下两个步骤,但是用户尝试执行三个步骤,则它不算作可能的组合。

else if (n==0) return 1;

如果剩余步骤数与用户尝试执行的可用步骤数匹配,则可能是组合。因此,返回1,因为这是可能的组合,应将其添加到有效组合的总数中。

else if (map[n]>-1) return map[n];

这是动态编程部分。假定数组中的所有值的值为-1。因此,如果该数字大于-1,则说明已经解决了该问题,因此请从步骤号n返回组合的总数,而不是对其进行求解。

`map[n] = countDP(n-1, map) + countDP(n-2, map) + countDP(n-3, map);`

return map[n]; }

最后,这部分解决了代码。可能组合的数量等于用户迈出1步可获得的可能组合数量+用户迈出2步可获得的可能组合数量+用户迈出可获得的可能的组合数量三个步骤。

例如,假设有5个步骤

一个简单的运行看起来像:

//The number of solutions from the fifth step

countDp(5) = countDp(4)+countDp(3)+countDp(2);

//Number of solutions from the fourth step

countDP(4) = countDp(3)+countDp(2)+countDp(1);

//Number of solutions from the third step

countDp(3) = countDp(2)+countDp(1)+countDp(0);

//Number of solutions from the second step

countDp(2) = countDp(1)+countDp(0)+countDp(-1);

//Number of solutions from the first step

countDp(1) = countDp(0) + countDp(-1)+countDp(-2);

//Finally, base case

countDp(0) = 1;

countDp(-1)= 0;

countDp(-2)= 0;

countDp(1) = 1+0+0 = 1;

countDp(2) = 1+1+0 = 2; //Dynamic programming: did not have to resolve for countDp(1), instead looked up the value in map[1]

countDp(3) = 2+1+1 = 4; //Dynamic programming, did not have to solve for countDp(1), countDp(2), instead looked up value in map[1] and map[2]

countDp(4) = 4+2+1=7 //Dynamic programming, did not have to solve for CountDp(3),CountDp(2), CountDp(1), just looked them up in map[3],map[2],map[1]

countDp(5)= 2+4+7=13 //Dynamic programming, just used map[4]+map[3]+map[2]

2020-12-03

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值