Climbing Stairs leetcode java


題目

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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM