LeetCode 70. Climbing Stairs
原题链接在这里:https://leetcode.com/problems/climbing-stairs/
题目:
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.
题解:
其实是Fibonacci Number. e.g. n = 100, 假设登到99台阶有m种方法,登到98台阶有n种方法,那么从99到100都是上一步,所以还是m种方法. 从98台阶登到100都是一次登两个台阶,还是n种方法,若果在98登一个台阶,就是到了99, 这种方法已经包含在最初登到99台阶的m种方法中了。
所以登到100的方法就是m+n.
Method 1: Time Complexity:O(2^n). Space: O(n), stack space.
Method 2: Time Complexity: O(n). Space: O(n).
Method 3: Time Complexity: O(n). Space: O(1).
AC Java:
1 public class Solution { 2 public int climbStairs(int n) { 3 /* 4 //Method 1 5 if(n == 0){ 6 return 1; 7 } 8 if(n == 1){ 9 return 1; 10 } 11 return climbStairs(n-1) + climbStairs(n-2); 12 */ 13 14 /* 15 //Method 2 16 int [] arr = new int[n+1]; 17 arr[0] = 1; 18 arr[1] = 1; 19 for(int i = 2; i <= n; i++){ 20 arr[i] = arr[i-1] + arr[i-2]; 21 } 22 return arr[n]; 23 */ 24 //Method 3 25 if(n == 1){ 26 return 1; 27 } 28 if(n == 2){ 29 return 2; 30 } 31 int first = 1; 32 int second = 2; 33 int res = 0; 34 for(int i = 3; i<=n; i++){ 35 res = first + second; 36 first = second; 37 second = res; 38 } 39 return res; 40 } 41 }
类似Fibonacci Number, Min Cost Climbing Stairs, New 21 Game, Domino and Tromino Tiling, Combination Sum IV.