LeetCode:Jump Game(Greedy DpUpdate)

problem:

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.

解决思路:由于每层最多可以跳 nums[i]步 亦可以1步或0步 我们可以每层每层的往上跳 看一下到达的最高层是否大于等于n

 1 class Solution {
 2 public:
 3     bool canJump(vector<int>& nums) {
 4         int n=nums.size();
 5         
 6         int maxreach=1;
 7         for(int i=0;i<maxreach && maxreach<n;i++)
 8             maxreach=max(maxreach,i+nums[i]+1);
 9         
10         return maxreach>=n;
11     }
12 };

 

这道题也可以用动规解决 need update

posted @ 2015-07-09 15:09  尾巴草  阅读(161)  评论(0编辑  收藏  举报