LeetCode——jump-game

Question

Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A =[2,3,1,1,4], returntrue.
A =[3,2,1,0,4], returnfalse.

Solution

  1. 动态规划。 判断前面的位置是否能达到当前位置。

  2. 时间复杂度O(n^2)

  3. 贪心算法。

  4. 时间复杂度O(n)

Code

// 动态规划
class Solution {
public:
    bool canJump(int A[], int n) {
        vector<bool> tb(n, false);
    	tb[0] = true;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (tb[j] && j + A[j] >= i) {
                    tb[i] = true;
                    break;
                }
            }
        }
        return tb[n - 1];
    }
};
// 贪心算法,如果数组的值表示只能走的步数,而不是至多走的步数,那么就只能用动态规划
class Solution {
public:
    bool canJump(int A[], int n) {
        int max = 0; // 当前能达到的最远坐标
        // 如果能达到的最远坐标都小于i了,那么也不用计算后面的了
        for (int i = 0; i < n && max >= i; i++) {
            if (A[i] + i > max)
                max = A[i] + i;
        }
        if (max >= n - 1)
            return true;
        else
            return false;
    }
};
posted @ 2017-10-31 18:02  清水汪汪  阅读(115)  评论(0编辑  收藏  举报