Climbing Stairs -- leetcode
发布时间:2020-12-13 20:06:57 所属栏目:PHP教程 来源:网络整理
导读:You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 此题用动太计划解决。 递归式为:dp[n] = dp[n⑴] dp[n⑵] 爬到第n层,有两种
You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 此题用动太计划解决。 递归式为:dp[n] = dp[n⑴] + dp[n⑵] 爬到第n层,有两种途径,1步从n⑴上来,1下跨两步从n⑵上来。 即要求出爬到第n层的所以方法,需知道爬到第n⑴层,n⑵层的方法。
关于出发点0层,可以定义为有1种方法,即不动。既不跨1步,也不跨两步,就到达。 比0层更低的,定义为0种办法。 这也可看做是Fibonacci求解。 0,1,2,3,5,8,13,21,34,...
class Solution {
public:
int climbStairs(int n) {
if (n == 0 || n == 1)
return 1;
int stepOne = 1,stepTwo = 1;
int allWays;
for (int i=2; i<=n; i++) {
allWays = stepOne + stepTwo;
stepTwo = stepOne;
stepOne = allWays;
}
return allWays;
}
}; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |