[LeetCode][Java] Climbing Stairs__Java

來源:互聯網
上載者:User
題目:

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? 題意:

假設爬梯子,你需要n步跑到頂。

每次你只能爬1步或者2步。最終你有多少種不同的方式爬到頂。


演算法分析:

    爬梯子問題實質上就是斐波那契數列:

 * 當n=1時,ways=1
 * 當n=2時,有[2] [1,1]兩種情況,ways=2
 * 當n=3時,有[1,1,1] [1,2] [2,1]三種情況,ways=3
 * 當n=4時,有[1,1,1,1] [2,2] [1,1,2] [1,2,1] [2,1,1]五種情況,ways=5
 * 當n=5時,有[1,1,1,1,1] [2,2,1] [2,1,2] [1,2,2] [1,1,1,2] [1,1,2,1] [1,2,1,1] [2,1,1,1]八種情況,ways=8
 * 當n>3時,n對應的情況數字為n-1和n-2之和。此時,規律正好和斐波那契數列出現的規律對應。
 * 斐波拉切數列是這樣一個數列:1、1、2、3、5、8、13、21、……在數學上,其被以遞迴的方法定義:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2)
代碼如下:

public class Solution {    //用遞迴逾時了 ==+   /*public  int climbStairs(int n)     {    int res = 0;if(n==0) res= 0;if(n==1) res= 1;if(n==2) res= 2;if(n>2) res= climbStairs(n-1)+climbStairs(n-2);return res;        }*/    //改用數組    public int climbStairs(int n)    {    int res[] = new int[n+1];int i=0;    for(i=0;i<n+1;i++)    {if(i==0) res[i]= 0;if(i==1) res[i]= 1;if(i==2) res[i]= 2;if(i>2)res[i]=res[i-1]+res[i-2];    }    return res[n];    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.