【Leetcode】Jump Game #55

来源:互联网 发布:阿里云搭建ftp 编辑:程序博客网 时间:2024/05/16 03:12
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.
url: https://leetcode.com/problems/jump-game/
基本思路:
采用动态规划,答案存储在vector ans中。
假定我们在判断第i元素是否可以到达last element,则
ans[i] = true, if
1.i element 可以直接到达最后, 或者
2. 有j在i+ nums[i]范围内可以到达最后
注意本题需要剪枝
<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">如果ans[j] == false,那我们可以直接从ans[k], k = j + nums[j] + 1 开始查起。从ans[j]到ans[k]之间的元素必为false</span>
<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">证明:</span>
如果ans[j] == false,且 j 至 j + nums[j] + 1元素间有一元素可以到达最后,
则ans[j]应该为true,与假设相反。
  bool canJump(vector<int>& nums) {        vector<bool> ans(nums.size(), false);        for (int i = nums.size()-1; i >= 0; --i)        {        int maxStep = nums[i];        int remainingStep = nums.size() - i - 1;        if (maxStep >= remainingStep)        {        ans[i] = true;        }        else {            int j = i+1;        while (j <= maxStep+i)        {        if (ans[j] == true)        {        ans[i] = true;        break;        }        j = j + nums[j] + 1;        }        }        }        return ans[0];    }

另附leetcode上一个不错的答案:
bool canJump(int* nums, int n) {    int goal=n-1, i;    for (i=n; i--;)        if (i+nums[i] >= goal)            goal=i;    return !goal;}


0 0
原创粉丝点击