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個台階的話,一共有幾種方法爬到頂端。
思路:
n<=1,此時只有一種。
n>1時,對於每一個台階i,要到達台階,最后一步都有兩種方法,從i-1邁一步,或從i-2邁兩步。
也就是說到達台階i的方法數=達台階i-1的方法數+達台階i-2的方法數。所以該問題是個DP問題。
d(0) = 1
d(1) = 1
d(2) = d(2-1) + d(2-2)
d(3) = d(3-1) + d(3-2)
……
好吧,狀態轉移方程其實就是Fibonacci數列。
代碼實現給出兩種方案吧:
python代碼如下:
1 class Solution(object): 2 def climbStairs(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 if n<=1: 8 return 1 9 res = [] 10 res.append(1) 11 res.append(1) 12 for i in range(2,n+1): 13 res.append(res[-1]+res[-2]) 14 return res[-1]
Java代碼如下:
1 public class Solution { 2 public int climbStairs(int n) { 3 if (n<=1) 4 return 1; 5 6 int oneStep=1,twoStep = 1,res = 0; 7 8 for (int i = 2; i <= n; i++) { 9 res = oneStep + twoStep; 10 twoStep = oneStep; 11 oneStep = res; 12 } 13 14 return res; 15 } 16 }
