題目:
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];
}
}