标签:
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
.
===========
非负数组,数组元素表示在当前位置能jump的最大距离,
问:是否能到达最后的位置?
----------
思路:正向贪心的思路,
每一步记住能够到达最远的距离,就好。
=====
code
class Solution { //本题正向贪心 public: bool canJump(vector<int>& nums) { int maxLocation;//当前可能到达的最大位置(下标) maxLocation = nums[0]; int length = nums.size(); for(int i = 0;i<length && maxLocation>=i;i++){
///maxLocation>=i 在这里是剪枝,遇到1,2,0.0.0.0.0.0.0....这样直接返回,无需遍历整个数组了。 maxLocation = max(maxLocation,i+nums[i]); } return maxLocation >= (length-1); } };
2,也可以采用爬楼梯方法
思路:
@int max_left bool canJump{ max_left = nums.size()-1; for(int i = nums.size()-2;i>=0;i--){ if(nums[i]+i>=max_left) max_left = i; } return max_left==0? }
标签:
原文地址:http://www.cnblogs.com/li-daphne/p/5611865.html