DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on • Updated on

Leetcode - 70. Climbing Stairs

Initial Solution

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
  let  dp = {

    }
    if(n<=2){
        return n
    }
    //5 steps
    if(n>2){
        if(dp.hasOwnProperty(n)){
            return dp[n]
        }else{
            dp[n] = climbStairs(n-1) + climbStairs(n-2)
        }
    }
    return dp[n]
};
Enter fullscreen mode Exit fullscreen mode

This solution is not efficient

Went through the solution - link

Solution with Dynamic Programming

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
 let one =  1  ;
 let two = 1 ; 
    for(let i = 1 ; i< n;i++){
        temp = one
        one = one + two;
        two = temp;
    }
    return one
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)