LeetCode070——爬楼梯

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82862289

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/climbing-stairs/description/

题目描述:

知识点:动态规划

思路:动态规划

状态定义:f(x) -------- 到达x + 1阶楼梯的方法数量

状态转移:
(1)当x等于0时,f(0) = 1

(2)当x等于1时,f(1) = 2

(3)当x大于等于2时,f(x) = f(x - 1) + f(x - 2)。

时间复杂度和空间复杂度均是O(n)。

JAVA代码:

public class Solution {

    public int climbStairs(int n) {
        int[] path = new int[n];
        if(n == 1 || n == 2){
            return n;
        }
        path[0] = 1;
        path[1] = 2;
        for (int i = 2; i < n; i++){
            path[i] = path[i - 1] + path[i - 2];
        }
        return path[n - 1];
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82862289