55. Jump Game

55. Jump Game

My Submissions
Question
Total Accepted: 65623  Total Submissions: 237785  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Array Greedy

此问题有意思............有待以后再次回来总结.......

卧槽,题目理解了半天,不会
我的翻译,一个非零数组,你现在站在数组的第一个位置,数组中的每一个元素表示你在那个位置所能往前跳的最大距离
那么问题来了,你能否跳到数组最后那个位置。举例A = [2,3,1,1,4], return true.
可行的走法:0-2-3-4(2-1-1达到4)
或者0-1-4(2(只跳了一步)-3达到4)
题目说这是贪心算法(总是贪心的往最远跳,即在遍历数组时获取能跳的最大距离),
采用贪心的思路,采用reach变量维护能到达最远处,即当前子问题的最优解。当遍历到i的时候,局部最优解为nums[pos]+pos,
因此,此时的全局最优解即为reach和nums[pos]+pos的最大值:reach = max(reach, nums[pos] + i)。


class Solution {
public:
    bool canJump(vector<int>& nums) {
        int reach = 0;
        for(int pos = 0; pos <= reach && pos < nums.size(); ++pos)//pos <= reach表示一定要能达到那个位置,否则跳出循环
             reach = max(reach, nums[pos] + pos);//获取站在当前位置能跳到的最大位置
        return reach >= nums.size() - 1;
    }
};


//深感罪劣深重,我还以为我贪心算法学得有多好呢.....结果...有待总结经验教训!
//参考来源:http://blog.csdn.net/makuiyu/article/details/44218439


稍稍优化一下,一旦达到要求就可以停止继续判断:(20ms——>16ms)

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int reach = 0;
        for(int pos = 0; pos <= reach && pos < nums.size(); ++ pos)//pos <= reach表示一定要能达到那个位置,否则跳出循环
          {   
              reach = max(reach, nums[pos] + pos);//获取站在当前位置能跳到的最大位置
              if(reach >= nums.size() - 1)
                  return true;
          }
        return false;
    }
};


贪心策略:总是获取当前看来所能获取的最优解,为了能获取全局最优,这个当前的最优解一定要能(需要证明)遍历出全局最优解!


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50472248

原作者博客:http://blog.csdn.net/ebowtang

你可能感兴趣的:(LeetCode,算法,面试,贪心策略)