Leetcode-070-climbing stairs

Time:2022-1-4

climb stairs

Title Description: suppose you are climbing stairs. You need n steps to reach the roof.

You can climb one or two steps at a time. How many different ways can you climb to the roof?

Note: given n is a positive integer.

See leetcode’s official website for an example.

Source: leetcode
Link: https://leetcode-cn.com/probl…
The copyright belongs to Lingkou network. For commercial reprint, please contact the official authorization, and for non-commercial reprint, please indicate the source.

Problem analysis

In a typical Fibonacci sequence, there are two walking methods to step n, either from step n-1 or from step n-2, so the total number of walking methods to step n is equal to the walking method of step n-1 plus the walking method of step n-2.

Solution 1: recursion

Call the same method recursively. First, if n is 1 or 2, return n directly; If n is greater than 2, the method is called recursivelyf(n) = f(n - 1) + f(n - 2)

Solution 2: iteration

First, if n is 1 or 2, return n directly; If n is greater than 2, record the two previous values as lastone and lasttwo respectively, and the current value is the sum of the two values, and then update the values of lastone and lasttwo until the iteration reaches n.

public class LeetCode_070 {
    /**
     *Recursion: time limit exceeded when submitting
     *
     * @param n
     * @return
     */
    public static int climbStairs(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        return climbStairs(n - 1) + climbStairs(n - 2);
    }

    /**
     *Iteration
     *
     * @param n
     * @return
     */
    public static int climbStairs2(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        int lastOne = 1, lastTwo = 2, result = -1;
        for (int i = 3; i <= n; i++) {
            result = lastOne + lastTwo;
            lastOne = lastTwo;
            lastTwo = result;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(climbStairs(45));
        System.out.println(climbStairs2(45));
    }
}

[daily message]Your good luck lies in your strength and your unknown efforts. The harder you work, the luckier you will be.