题目:
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?
分析:
这道题属于动态规划里可能解个数的题。按照分析动态规划问题的方法进行分析:
1. 每个状态f[n]代表上到第n个台阶的所有可能个数
2. 每次只能上1台或2台,所有f[n] = f[n-1] + f[n-2],即上一台到n还是上两台到n
3. 开始的状态f[1] = 1,f[2] = 2
4. 结果为上到第n台的f[n]
Java代码实现:
public class Solution {
public int climbStairs(int n) {
if(n==0)
return 0;
if(n==1)
return 1;
if(n==2)
return 2;
int[] solution = new int[n];
solution[0] = 1;
solution[1] = 2;
for(int i=2;i<n;i++)
{
solution[i] = solution[i-1] + solution[i-2];
}
return solution[n-1];
}
}