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