Explain this dynamic programming climbing n-stair code

前端 未结 2 1000
说谎
说谎 2020-12-15 22:58

Problem is

\"You are climbing a stair case. Each time you can either make 1 step or 2 steps. The staircase has n steps. In how many distinct ways can you climb the s

相关标签:
2条回答
  • 2020-12-15 23:37

    Climbing Stairs Using DP

    class Solution {
       public:
         int climbStairs(int n) {
        int dp[n+1];
    
        if (n <= 1)
            return 1;
    
        if (n ==2)
            return 2;
    
        dp[0] = 1;
        dp[1] = 1;
        dp[2] = 2;
    
        for (int i = 3; i <=n; i++){
            dp[i] = dp[i-1]+dp[i-2];
        }
    
        return dp[n];
       }};
    
    0 讨论(0)
  • 2020-12-15 23:47

    Well, first you need to understand the recursive formula, and how we derived the iterative one from it.

    The recursive formula is:

    f(n) = f(n-1) + f(n-2)
    f(0) = f(1) = 1
    

    (f(n-1) for one step, f(n-2) for two steps, and the total numbers is the number of ways to use one of these options - thus the summation).

    If you look carefully - this is also a well known series - the fibonacci numbers, and the solution is simply calculating each number buttom-up instead of re-calculating the recursion over and over again, resulting in much more efficient solution.

    0 讨论(0)
提交回复
热议问题