DEV Community

duccanhole
duccanhole

Posted on

code every day with me

--DAY 13--

Hi, I am going to make #100DaysOfCode Challenge. Everyday I will try solve 1 problem from leetcode or hackerrank. Hope you can go with me until end.
Now let's solve problem today:

  • Problem: Climbing Stairs
  • Detail: here
  • Idea: use recursion
    • There are two way to climb to n'th stair: climb 1 step from n'th-1 stair or climb 2 steps from n'th-2 stair
    • Similar to Fibonacci
  • My solution (javascript): With recursion
var climbStairs = function(n) {
    if(n==1||n==2) return n;
    return climbStairs(n-1)+climbStairs(n-2);
};
Enter fullscreen mode Exit fullscreen mode

No recursion

var climbStairs = function(n) {
    if(n==1||n==2) return n;
    let dp=[];
    dp[0]=1; dp[1]=2;
    for(let i=2;i<n;i++){
        dp[i]=dp[i-1]+dp[i-2];
    }
    return dp[n-1];
};
Enter fullscreen mode Exit fullscreen mode

-->If you have better solution or any question, please comment below. I will appreciate.

Top comments (0)