LeetCode:70. Climbing Stairs(爬楼梯问题)

You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example 1:

Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

方法1:开始用的递归算法,由于效率不高,所以就换成了方法2 ,带记忆的动态规划 

package leetcode;

import org.junit.Test;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: ClimbingStairs
 * @Description: TOTO
 * @date 2018/12/5 16:22
 **/


public class ClimbingStairs {
    @Test
    public void fun() {
        long startTime = System.currentTimeMillis();
        int n = 44;
        int num = climbStairs2(n);
        long endTime = System.currentTimeMillis();
        System.out.println(num);
        System.out.println((endTime-startTime)/1000.0+"s");
    }

    private int climbStairs2(int n) {
        if (n == 0) {
            return 0;
        } else if (n == 1) {
            return 1;
        } else if (n == 2) {
            return 2;
        } else {
            return climbStairs2(n - 1) + climbStairs2(n - 2);
        }
    }
}

时间复杂度:O(n)

空间复杂度:O(n)


方法2:利用动态规划进行求解

package leetcode;

import org.junit.Test;

/**
 * @author zhangyu
 * @version V1.0
 * @ClassName: ClimbingStairs
 * @Description: TOTO
 * @date 2018/12/5 16:22
 **/


public class ClimbingStairs {
    @Test
    public void fun() {
        long startTime = System.currentTimeMillis();
        int n = 44;
        int num = climbingStairs(n);
        long endTime = System.currentTimeMillis();
        System.out.println(num);
        System.out.println((endTime-startTime)/1000.0+"s");
    }

    // 动态规划,记忆算法
    private int climbingStairs(int n) {
        if (n == 1) {
            return 1;
        }
        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];
    }
}

时间复杂度:O(n)

空间复杂度:O(n)

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/84839426