2019年10月5日
Leetcode 70. Climbing Stairs
C++, LeetCode, 算法, 编程
0 Comments
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?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
解析:
斐波那契数列问题。n=0时,结果为0;n=1时,结果为1;n=2时,可以两步每一步1个台阶,也可以一步。当台阶数为n时,可以从n-1处一步台阶过来,也可以从n-2处两步台阶过来。因此当前的结果只与前两个结果有关。
解法1:动态规划
class Solution {
public:
int climbStairs(int n) {
vector<int> dp(n, 0);
if(n==1)
return 1;
if(n==2)
return 2;
dp[0] = 1;
dp[1] = 2;
for(int i=2; i < n; i++)
dp[i] = dp[i-1] + dp[i-2];
return dp[n-1];
}
};
运行结果: 
解法2:
由上面分析可知道,当前结果只与前两个结果相关,因此定义两个变量,存放前两个的数值。具体代码如下:
class Solution {
public:
int climbStairs(int n) {
int prev = 0;
int cur = 1;
for(int i=1; i<=n; ++i)
{
int temp = cur;
cur += prev;
prev = temp;
}
return cur;
}
};
运行结果: 