70. Climbing stairs (implemented in java) - LeetCode

topic

70. Climb stairs

Suppose you are climbing stairs. It takes n steps to reach the top of the building.

You can climb 1 or 2 steps each time. How many different ways do you have to climb to the top of a building?

Note: Given n is a positive integer.

Example 1:

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

Example 2:

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

Solution 1: Recursion

/**
 * 思路:
 * 通过观察爬楼梯符合斐波那契数
 * 递归解决
 */
    public int climbStairs(int n) {
    
    
        if (n<=2)return n;
        return climbStairs(n-1)+climbStairs(n-2);
    }

Time complexity: On^2

Space complexity: O1
Insert picture description here

Solution 2: Memory array

/**
 * 思路:
 * 通过观察爬楼梯符合斐波那契数
 * 递归解决
 * 加入记忆数组,如果值在记忆数组中存在直接返回
 */
    public int climbStairs(int n) {
    
    
        int memory[]=new int[n+1];
        return recursive(memory,n);
    }

    private int recursive(int[] memory, int n) {
    
    
        if(n<=2)return n;
        if (memory[n]!=0)return memory[n];
        memory[n]=recursive(memory,n-1)+recursive(memory,n-2);
        return memory[n];
    }

Time complexity: On

Space complexity: On
Insert picture description here

Solution 3: Iteration (accumulation)

/**
 * 思路:
 * 通过观察爬楼梯符合斐波那契数
 * 累加的求出第n层有多少策略
 */
    public int climbStairs(int n) {
    
    
        if(n<=2)return n;
        int fist=1,second=2,result=0;
        for (int i=3;i<=n;i++){
    
    
            result=fist+second;
            fist=second;
            second=result;
        }
        return result;
    }

Time complexity: On

Space complexity: O1
Insert picture description here

Solution 4: Iteration (array)

/**
 * 思路:
 * 通过观察爬楼梯符合斐波那契数
 * 数组存放所有的fib数
 */
    public int climbStairs(int n) {
    
    
        if(n<=2)return n;
        int result[]=new int[n];
        result[0]=1;
        result[1]=2;
        for (int i=2;i<n;i++){
    
    
            result[i]=result[i-1]+result[i-2];
        }
        return result[n-1];
    }

Time complexity: On

Space complexity: On
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_38783664/article/details/111293548