題目:
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?
題解:
這道題就是經典的講解最簡單的DP問題的問題。。
假設梯子有n層,那麼如何爬到第n層呢,因為每次只能怕1或2步,那麼爬到第n層的方法要麼是從第n-1層一步上來的,要不就是從n-2層2步上來的,所以遞推公式非常容易的就得出了:
dp[n] = dp[n-1] + dp[n-2]
如果梯子有1層或者2層,dp[1] = 1, dp[2] = 2,如果梯子有0層,自然dp[0] = 0
程式碼如下:
1 public int climbStairs(int n) {
2 if(n==0||n==1||n==2)
3 return n;
4 int [] dp = new int[n+1];
5 dp[0]=0;
6 dp[1]=1;
7 dp[2]=2;
8
9 for(int i = 3; i<n+1;i++){
10 dp[i] = dp[i-1]+dp[i-2];
11 }
12 return dp[n];
13 }
2 if(n==0||n==1||n==2)
3 return n;
4 int [] dp = new int[n+1];
5 dp[0]=0;
6 dp[1]=1;
7 dp[2]=2;
8
9 for(int i = 3; i<n+1;i++){
10 dp[i] = dp[i-1]+dp[i-2];
11 }
12 return dp[n];
13 }