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 ;= <code>[2,3,1,1,4]</code>, ;return <code>true</code>.
A ;= <code>[3,2,1,0,4]</code>, ;return <code>false</code>.
贪心法,每次跳跃一步,可跳步数减去1,如果新的位置步数大于剩余步数,使用新的步数继续移动,如果可跳步数小于0且还没到最后一个步数,那么失败。
; ;<pre> ;1 ;class ;Solution ;{
;2 ;public:
;3 ; ; ; ; ;bool ;canJump(vector<int>& ;nums) ;{
;4 ; ; ; ; ; ; ; ; ;if(nums.size() ;== ;0){
;5 ; ; ; ; ; ; ; ; ; ; ; ; ;return ;true;
;6 ; ; ; ; ; ; ; ; ;}
;7 ; ; ; ; ; ; ; ; ;
;8 ; ; ; ; ; ; ; ; ;int ;reach ;= ;nums[0];
;9 ; ; ; ; ; ; ; ; ;for(int ;i ;= ;1; ;i ;< ;nums.size(); ;i ;++){
10 ; ; ; ; ; ; ; ; ; ; ; ; ;reach--;
11 ; ; ; ; ; ; ; ; ; ; ; ; ;
12 ; ; ; ; ; ; ; ; ; ; ; ; ;if(reach ;< ;0){
13 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;return ;false;
14 ; ; ; ; ; ; ; ; ; ; ; ; ;}
15 ; ; ; ; ; ; ; ; ; ; ; ; ;
16 ; ; ; ; ; ; ; ; ; ; ; ; ;if(reach ;< ;nums[i]){
17 ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;reach ;= ;nums[i];
18 ; ; ; ; ; ; ; ; ; ; ; ; ;}
19 ; ; ; ; ; ; ; ; ;}
20 ; ; ; ; ; ; ; ; ;return ;true;
21 ; ; ; ; ;}
22 ;};</pre> ; ;