[LeetCode-Java Exercises] 70. Climbing stairs (simple)

1. Title description

Insert picture description here

2. Problem solving ideas

We use f(x) to represent the number of plans to climb to the xth step, considering that the last step may have crossed one step or two steps, so we can list the following formula:
f(x) = f (x-1) + f(x-2)
It means that the number of plans to climb to the xth step is the sum of the number of plans to climb to the x−1 step and the number of plans to climb to the x−2 step . It is easy to understand, because each time you can only climb 1 or 2 levels, f(x) can only be transferred from f(x−1) and f(x−2), and here to count the total number of solutions, we need Sum the contributions of these two items.
The above is the transfer equation of dynamic programming, let's discuss the boundary conditions below. We started to climb from level 0, so we can see that there is only one plan from level 0 to level 0, that is, f(0)=1; there is only one plan from level 0 to level 1. , That is, climb one level, f(1) = 1. These two are used as boundary conditions to continue to deduce the correct result of the nth level. We might as well write a few items to verify. According to the transfer equation, we get f(2)=2, f(3)=3, f(4)=5,..., we enumerate these conditions and find the result of the calculation. is correct.
It is not difficult for us to use the transfer equation and boundary conditions to give a realization that both the time complexity and the space complexity are O(n), but because f(x) here is only equal to f(x−1) and f(x−2) ) Is relevant, so we can optimize the space complexity to O(1) using the "rolling array idea".

3. Code implementation

class Solution {
    
    
    public int climbStairs(int n) {
    
    
        int p = 0, q = 0, r = 1;
        for (int i = 1; i <= n; i++) 
        {
    
    
            p = q; 
            q = r; 
            r = p + q;
        }
        return r;
    }
}

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/114109583