55. Jump Game

来源:互联网 发布:比特币算法漏洞 编辑:程序博客网 时间:2024/06/10 19:11

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], return true.

A = [3,2,1,0,4], return false.

思路:维护一个bool数组isGood来记录nums中每个元素是否是“好”元素(即通过它可以跳到最后)。isGood全部初始化为false,最后一个为true。然后从后往前遍历,更新每个元素的isGood值,最后得到的isGood[0]即为所求答案。

class Solution {public:    bool canJump(vector<int>& nums) {        int n = nums.size();        if(n == 1) return true;        bool isGood[n] = {false};        isGood[n-1] = true;        for (int i = n - 2; i >= 0; i--) {            int check = (nums[i] <= n-1-i) ? nums[i] : n-1-i;            bool isIGood = false;            for (int j = i; j <= i + check; j++) {                if (isGood[j]) {                    isGood[i] = true;                    isIGood = true;                    break;                }            }        }        return isGood[0];    }};
原创粉丝点击