跳跃游戏

题源:leetcode

链接:https://leetcode-cn.com/problems/jump-game/

 贪心算法:

可以发现,只要达到当前最大路程,那么这个范围内的所有格子都可以走到,所以我们只要遍历所有可以走到的格子,看他们最远是否走到终点即可。

代码:

 1 class Solution {
 2 public:
 3     bool canJump(vector<int>& nums) {
 4         int size = nums.size();
 5         int cover = 0;
 6 
 7         if(size == 1) return true;
 8         
 9         for(int i = 0; i<size;i++){
10             if(i>cover) 
11                 break;
12             cover = max(cover,nums[i]+i);
13             if(cover >= size-1) return true;
14         }
15         return false;
16         
17         }
18 };
原文地址:https://www.cnblogs.com/hosheazhang/p/15057711.html