Problem:
Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is at that position.
Determine if you is able to reach the last index.
For example:
A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
Hide TagsArray GreedyTest instructions: Jumping from the starting point, the maximum number of steps per jump is the array value for that position, to determine if you can finally jump to the last position
Thinking:
(1) At the beginning of the idea of Dfs, each of the arrival of the node for deep search, but due to less boundary conditions, time complexity will expand sharply, not feasible
(2) Another method is to use greedy strategy, before a jump Game topic, the number of steps is also the use of greed. The idea is to use the weighted method of a[base+step]+step to measure the merits and demerits of each choice, and to determine whether or not to reach or exceed the last digit of the array when jumping to the first 0.
What is assumed here is that each jump chooses to jump to the farthest, and if you can finally jump to the last or last one of the array, then there must be a way to jump to the last one.
This hypothesis is easy to prove to be true, because the last step of jumping can choose any step between the 0~step
Code
Class Solution {public: bool Canjump (int a[], int n) { if (n==1) return true; int index=0; int _max=0; while (Index<n) { if (_max>=n-1) return true; if (a[index]==0) { if (_max<n-1) return false; else return true; } int Tmp=a[index]; int flag=0; for (int i=1;i<=a[index];i++) { if (a[index+i]+i>=tmp) { tmp=a[index+i]+i; flag=i; } } Index+=flag; _max=a[index]+index;}} ;
Leetcode | | 55. Jump Game