《剑指offer》8.跳台阶

题目地址:https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&tqId=11161&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

解题思路:典型的动态规划方法,这是最简单的动态规划过程,这题和斐波那契数列类似,两种解法,第一种是递归调用,时间复杂度为O(n),空间复杂度 为O(n)。

public class Solution {
    public int JumpFloor(int target) {
        if(target<=0)
            return 0;
        if(target==1)
            return 1;
        if(target==2)
            return 2;
        return JumpFloor(target-1)+JumpFloor(target-2);
    }
}

第二种是是循环的方法,时间复杂度为O(n),空间复杂度为O(1)。

public int JumpFloor(int n) {
    if (n <= 1)
        return n;
    int pre2 = 0, pre1 = 1;
    int result = 0;
    for (int i = 1; i <= n; i++) {
        result = pre2 + pre1;
        pre2 = pre1;
        pre1 = result;
    }
    return result;
}

猜你喜欢

转载自blog.csdn.net/qq_28900249/article/details/89278258
今日推荐