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?
标准Dynamic Programming,爬第n个台阶的最后一步可以爬1格或2格,因此f(n)=f(n-1)+f(n-2).
f(1)=1,f(2)=2
public class Solution {
public int climbStairs(int n) {
//f(n) = f(n-1)+f(n-2)
int[] result = new int[n + 1];
if(n == 0)
return 0;
if(n == 1)
return 1;
if(n == 2)
return 2;
result[1] = 1;
result[2] = 2;
for(int i = 3; i <= n; i++){
result[i] = result[i - 1] + result[i - 2];
}
return result[n];
}
}