Skip to content

Latest commit

 

History

History
105 lines (91 loc) · 2.39 KB

70. Climbing Stairs.md

File metadata and controls

105 lines (91 loc) · 2.39 KB

leetcode Daily Challenge on July 31th, 2020.


Difficulty : Easy

Related Topics : Dynamic Programming


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 top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

Solution

same as 518. Coin Change 2.

  • mine
    • Java
      • Brute Force Time Limit Exceeded

        int res = 0;
        public int climbStairs(int n) {
            next(0,n);
            return res;
        }
        
        public void next(int i, int sum){
            if(i < sum){
                next(i + 1, sum);
                next(i + 2, sum);
            }else if(i == sum){
                res++;
            }
        }
        
      • Dynamic Programming Runtime: 0 ms, faster than 100.00%, Memory Usage: 35.8 MB, less than 5.26% of Java online submissions

        //O(N)time O(N)space
        public int climbStairs(int n) {
            int[] res = new int[n + 1];
            res[0] = 1;
            res[1] = 1;
            for(int i = 2; i <= n; i++){
                res[i] += res[i-1] + res[i-2];
            }
            return res[n];
        }
        

  • the leetcode solution
  • Recursion with Memoization Runtime: 0 ms, faster than 100.00%, Memory Usage: 35.8 MB, less than 5.26% of Java online submissions
    //O(N)time O(N)space
    public int climbStairs(int n) {
        int memo[] = new int[n + 1];
        return climb_Stairs(0, n, memo);
    }
    public int climb_Stairs(int i, int n, int memo[]) {
        if (i > n) {
            return 0;
        }
        if (i == n) {
            return 1;
        }
        if (memo[i] > 0) {
            return memo[i];
        }
        memo[i] = climb_Stairs(i + 1, n, memo) + climb_Stairs(i + 2, n, memo);
        return memo[i];
    }