标签:leetcode 动态规划 爬楼梯 stair climb
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-1] + dp[n-2]
爬到第n层,有两种途径,一步从n-1上来,一下跨两步从n-2上来。
即要求出爬到第n层的所以方法,需知道爬到第n-1层,n-2层的方法。
关于起点0层,可以定义为有一种方法,即不动。既不跨一步,也不跨两步,就达到。
比0层更低的,定义为0种办法。
这也可看作是Fibonacci求解。
0, 1, 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; } };
标签:leetcode 动态规划 爬楼梯 stair climb
原文地址:http://blog.csdn.net/elton_xiao/article/details/44954673