1ms JAVA solution easy to understand with DP


  • 6
    V

    public class Solution {

    int result;
    HashMap<Integer, Integer> memo = new HashMap<Integer, Integer>();
    
    public int climbStairs(int n) {
        if(n < 2) {
            return 1;
        }
        if(memo.containsKey(n)) {
            return memo.get(n);
        }
        result = climbStairs(n-1) + climbStairs(n-2);
        memo.put(n,result);
        return result;
    }
    

    }


  • 0
    I

    public class Solution {
    public int climbStairs(int n) {
    int i, temp;
    int[] num={1,2};
    if (n==1) return 1;
    if (n==2) return 2;
    for(i=0;i<n-2;i++){
    temp=num[1];
    num[1]=num[0]+num[1];
    num[0]=temp;
    }
    return num[1];
    }
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.