题目:
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 step + 1 step
- 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
解法1:递归加记忆数组
本质上是斐波那契数列问题,爬到第n层,要么从n-1层一层上来,要么从n-2层爬两层上来
得递推公式:dp[n] = dp[n-1] + dp[n-2]
初始值,n=1为1,n=2为2
直接用递归做,会超时,我们用一个数组记录下结果,避免不必要的计算
c++:
class Solution {
public:
int climbStairs(int n) {
f = vector<int>(n+1,0);
if(n == 1) return 1;
f[1] = 1;
f[2] = 2;
return dfs(n);
}
private:
vector<int> f;
int dfs(int n){
if(n == 1) return f[1];
if(n == 2) return f[2];
if(f[n] > 0) return f[n];
else return f[n] = dfs(n-1) + dfs(n-2);
}
};
java:
class Solution {
private int[] f = null;
public int climbStairs(int n) {
f = new int[n+1];
if(n == 1) return 1;
f[1] = 1;
f[2] = 2;
return dfs(n);
}
private int dfs(int n){
if(n == 1) return f[1];
if(n == 2) return f[2];
if(f[n] > 0) return f[n];
else return f[n] = dfs(n-1) + dfs(n-2);
}
}
python:
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
self.f = [0 for i in xrange(n+1)]
if n == 1: return 1
self.f[1] = 1
self.f[2] = 2
return self.dfs(n)
def dfs(self, n):
if n == 1: return self.f[1]
if n == 2: return self.f[2]
if self.f[n] > 0: return self.f[n]
else:
self.f[n] = self.dfs(n-1) + self.dfs(n-2)
return self.f[n]
解法2:
动态规划
c++:
class Solution {
public:
int climbStairs(int n) {
vector<int> f(n+1,0);
if(n == 1) return 1;
f[1] = 1;
f[2] = 2;
for(int i=3; i<=n;i++){
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
};
java:
class Solution {
public int climbStairs(int n) {
int[] f = new int[n+1];
if(n == 1) return 1;
f[1] = 1;
f[2] = 2;
for(int i=3; i<=n;i++){
f[i] = f[i-1] + f[i-2];
}
return f[n];
}
}
python:
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
f = [0 for i in xrange(n+1)]
if n == 1: return 1
f[1] = 1
f[2] = 2
for i in xrange(3,n+1):
f[i] = f[i-1] + f[i-2];
return f[n]