[leetcode]70.Climbing Stairs
阿新 • • 發佈:2018-09-30
ret reac The solution 計算 not 動態規劃 man return
題目
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 step + 1 step
- 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
解法一
思路
要走到第n個階梯,最後一步只有兩種,先走到第n-1個階梯,然後再走一步,或者先走到第n-2個階梯,然後再走2步;所以走到第n個階梯的方法數=走到第n-1個階梯的方法數+走到第n-2個階梯的方法數,很明顯這是一個遞歸。時間復雜度接近2的n次方(想象一下遞歸的樹)。但是很不幸,這種方法超時了。。。不過還是寫出來。
代碼
class Solution {
public int climbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
else return climbStairs(n-1) + climbStairs(n-2);
}
}
解法二
思路
遞歸中有太多重復計算的東西,所以我們可以用動態規劃的思想,自下而上,進行叠代計算。時間復雜度為O(n),空間復雜度為O(1)。
代碼
class Solution { public int climbStairs(int n) { HashMap<Integer, Integer> map = new HashMap<Integer,Integer>(); if(n == 1) return 1; if(n == 2) return 2; int a = 1; int b = 2; int temp = 0; for(int i = 2; i < n; i++){ temp = a + b; a = b; b = temp; } return temp; } }
[leetcode]70.Climbing Stairs