题目描述:
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.
解题思路:
最先想起来的是递归
class Solution {
public int climbStairs(int n) {
if(n==1)
return 1;
if(n==2)
return 2;
return climbStairs(n-1)+climbStairs(n-2);
}
}
但是,结果是超时,所以可以用动态规划来暂存中间结果
class Solution {
public int climbStairs(int n) {
//状态转移方程: D(n) = D(n-1)+D(n-2)
int[] D = new int[n+1];
D[0] = 1;
D[1] = 1;
for(int i=2;i<=n;i++){
D[i] = D[i-1]+D[i-2];
}
return D[n];
}
}