要求:
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?
注意:基本动态规划问题,只要写出状态转移方程就可以了。当到了第i个阶梯时,它之前的状态只有两种:i-1或i-2。f(i)表示到第i个阶梯的方法总数,那么有:f(i) = f(i-1) + f(i-2),因此,只要用一个数组来保存每次的状态就可以了(也可以用两个变量保存,空间复杂度低)
public int climbStairs(int n) {
if (n <= 1)
return 1;
int[] k = new int[n + 1];
k[1] = 1;
k[2] = 2;
for (int i = 3; i <= n; i++) {
k[i] = k[i - 1] + k[i - 2];
}
return k[n];
}