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 the tNop. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
這個題很顯然是用動態規划的做法,人在跳最后一步時,有兩種可能,人可能跳一個台階,也可能跳兩個台階,如果說n個台階的走法是F(n),那么F(n) = F(n-1) + F(n-2),當n=1時,F(n) = 1,當n = 2時,F(n) = 2;
public int climbStairs1(int n) { if (n <= 0) return -1; else if (n == 1) return 1; else if (n == 2) return 2; else return climbStairs1(n - 1) + climbStairs1(n - 2); }
這種解法時間復雜度很糟糕,在編譯器中,每次遞歸計算的值都沒有被保存下來,不建議采用。為了每次遞歸計算的值保存下來,我們創建一個空間大小為n+1的數組dp[],空間和時間復雜度都是O(n)。
public int climbStairs2(int n) { if (n <= 0) return -1; else if (n == 1) return 1; int[] dp = new int[n + 1]; dp[1] = 1; dp[2] = 2; for (int i = 3; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2]; return dp[n]; }
在計算的過程中我們發現,dp[]數組滿足斐波那契數列關系,可以利用這一特點只定義三個變量,由此來降低空間復雜度,使得空間復雜度優化到O(n).
public int climbStairs3(int n) { if (n == 1) return 1; int first = 1; int second = 2; for (int i = 3; i <= n; i++) { int third = first + second; first = second; second = third; } return second; }