Climbing stairs with dynamic programming

Continue to create, accelerate growth! This is the first day of my participation in the "Nuggets Daily New Plan · October Update Challenge", click to view the details of the event

Dynamic programming is a mathematical idea of ​​solving decision-making problems in stages. It solves complex problems by decomposing the original problem into simple sub-problems.

climb stairs

Suppose you are climbing stairs. You need  n steps to get to the top.

You can climb  one 1 or  2 more steps at a time. How many different ways can you get to the top of a building?

Example 1:

输入:n = 2
输出:2
解释:有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶

复制代码

Example 2:

输入:n = 3
输出:3
解释:有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
复制代码

law of violence

We can combine all possible steps to climb and solve directly recursively.

aaa.png.png

As shown in the figure above, the brute force solution will have many repeated branches, and the time complexity must be very high.

Dynamic programming:

Since you can climb 1 or 2 steps at a time, you can go up to the nth step from the n-2 or n-1.

There are several ways to use f[n] to represent n steps, then f[n]=f[n-1]+f[n-2];

Consider two special cases

  • When n=1, f(1)=1, that is, there is only one move.
  • When n=2, f(2)=2, that is, there are two ways to move: 1st order + 1st order or 2nd order

accomplish

class Solution {
    public int climbStairs(int n) {
        if (n==1){
           return 1;
        }else if (n==2){
            return 2;
        }else{  
            int[] dp=new int[n+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];
        }
    }
}
复制代码
Complexity Analysis:
  • Time complexity O(n): It takes one loop to calculate f(n).
  • Space complexity O(n): The dp array is used to record the moves at the nth order. However, since f(n) in this topic is only related to the first two items f(n-1) and f(n-2), we can directly use two variable records, and the space complexity can be reduced to O(1) )
class Solution {
public:
    int climbStairs(int n) {
        int p1 = 0, p2 = 0, current = 1;
        for (int i = 1; i <= n; ++i) {
            p1 = p2; 
            p2 = current; 
            current = p1 + p2;
        }
        return current;
    }
};
复制代码
  • Time complexity: O(n)
  • Space Complexity: O(1)

Guess you like

Origin juejin.im/post/7149889507775479821