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?spa
有n階,第一次邁一階,剩餘的跟n-1的次數相同,或者第一次邁2階,剩餘的跟n-2的次數相同。斐波那契數列。code
代碼一:blog
1 public int climbStairs(int n) { 2 int[] a=new int[n+1]; 3 if(n<3) 4 return n; 5 else{ 6 a[1]=1; 7 a[2]=2; 8 for(int i=3;i<=n;i++){ 9 a[i]=a[i-1]+a[i-2]; 10 } 11 return a[n]; 12 } 13 }
代碼二it
1 public int climbStairs(int n){ 2 if(n<3) 3 return n; 4 else{ 5 int beforeOne=2,beforeTwo=1,sum = 0; 6 for(int i=3;i<=n;i++){ 7 sum=beforeOne+beforeTwo; 8 beforeTwo=beforeOne; 9 beforeOne=sum; 10 } 11 return sum; 12 } 13 }
注意事項io
下面的代碼會超時class
1 public class Solution { 2 public int climbStairs(int n) { 3 if(n==1||n==2) 4 return n; 5 else 6 return climbStairs(n-1)+climbStairs(n-2); 7 } 8 }