Iterrative 实现递归
public class Solution {
public int climbStairs(int n) {
int prev=0, cur=1;
for(int i=1; i<=n; i++){
int tmp=cur;
cur += prev;
prev=tmp;
}
return cur;
}
}
DP实现:
public class Solution {
public int climbStairs(int n) {
int[] f=new int[n+1];
int[] fun=new int[n+1];
for(int i=0; i<=n; i++){
f[i]=i;
}
for(int i=3; i<=n; i++){
f[i]=f[i-1]+f[i-2];
}
return f[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?