贪心

55. Jump Game(贪心)

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

 

45. 跳跃游戏 II

 1 class Solution {
 2 public:
 3 //The main idea is based on greedy. Let's say the range of the current jump is [curBegin, curEnd], curFarthest is the farthest point that all points in [curBegin, curEnd] can reach. Once the current point reaches curEnd, then trigger another jump, and set the new curEnd with curFarthest, then keep the above steps, as the following:
 4 
 5     int jump(vector<int>& nums) 
 6     {
 7         int max_far = 0;// 目前能跳到的最远位置
 8         int step = 0;   // 跳跃次数
 9         int end = 0;    // 上次跳跃可达范围右边界(下次的最右起跳点)
10         for (int i = 0; i < nums.size() - 1; i++)
11         {
12             max_far = std::max(max_far, i + nums[i]);
13             // 到达上次跳跃能到达的右边界了
14             if (i == end)
15             {
16                 end = max_far;  // 目前能跳到的最远位置变成了下次起跳位置的有边界
17                 step++;         // 进入下一次跳跃
18             }
19         }
20         return step;
21     }
22 };

 

 

posted @ 2021-11-20 19:44  乐乐章  阅读(28)  评论(0编辑  收藏  举报