70. Climbing Stairs(python+cpp)
阿新 • • 發佈:2018-12-17
題目:
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? Note: Given n will be a positive integer. Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to thetop. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
解釋: 斐波那契數列。動態規劃經典題目。可以用遞迴做也可以用迴圈做,遞迴做會重複計算所以儘量不要遞迴,迴圈做的時候,由於之和前兩個狀態有關,所以可以只用兩個標量即可,不一定非要用一個數組儲存結果。 迴圈解法,用陣列儲存,python程式碼:
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
#迴圈解法,用陣列
dp=[0]*(n+1)
dp[0]=1
dp[1]=1
for i in range(2,n+1):
dp[i]=dp[i-2]+dp[i-1]
return dp[n]
用兩個變數即可,python程式碼:
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
#迴圈解法,用兩個變數
if n==0 or n==1:
return 1
first,second=1,1
for i in range(2,n+1):
first,second=second,first+second
return second
遞迴會超時,因為會重複計算比如說,計算(n-1)
的又把(n-2)
計算了一遍,沒有充分利用遞迴的結果,python程式碼:
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
#瘋狂的遞迴
if n==0 or n==1:
return 1
return self.climbStairs(n-2)+self.climbStairs(n-1)
c++程式碼:
class Solution {
public:
int climbStairs(int n) {
if (n == 0 || n == 1)
return 1;
int pre = 1;
int current = 1;
for (int i = 2; i <= n; i++) {
int temp = current + pre;
pre = current;
current = temp;
}
return current;
}
};
總結: 對於遞迴的問題,用迴圈(陣列儲存)有時候會更快,而且如果需要的前面的狀態是很少的而且前面的資訊在最後不再需要的話,可以只用少量變數儲存臨時結果。