码迷,mamicode.com
首页 > 其他好文 > 详细

045. Jump Game II

时间:2016-10-16 11:25:03      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

方法一:遍历所有可能的情况,复杂度O(N^2),超时

 1 class Solution {
 2 public:
 3     int jump(vector<int>& nums) {
 4     if (nums.size() < 2) return 0;
 5         else {
 6             vector<int> max_jump(nums.size(), static_cast<int>(nums.size()));
 7             vector<int> reach(nums.size(), 0);
 8             max_jump[0] = 0;
 9             reach[0] = 1;
10             for (size_t i = 1; i < nums.size(); ++i) {
11                 for (int j = 0; j < i; ++j) {
12                     if (reach[j] && nums[j] >= i - j) {
13                         reach[i] = 1;
14                         if (max_jump[j] + 1 < max_jump[i]) max_jump[i] = max_jump[j] + 1;
15                     }
16                 }
17             }
18             return max_jump[nums.size() - 1];
19         }
20     }
21 };

 

方法二:贪心,每次都跳最大的距离,时间复杂度O(N)

 1 class Solution {
 2 public:
 3     int jump(vector<int>& nums) {
 4         if (nums.size() < 2) return 0;
 5         else {
 6             int left = 0, right = 0;
 7             int step = 0;
 8             int pos = 0;
 9             while (left <= right) {
10                 int new_right = right;
11                 ++step;
12                 for (int i = left; i <= right; ++i) {
13                     pos = i + nums[i]; 
14                     if (pos >= nums.size() - 1) return step;
15                     if (pos > new_right) new_right = pos;
16                 }
17                 left = right + 1;
18                 right = new_right;
19             }
20             return step;
21         }
22     }
23 };

 

045. Jump Game II

标签:

原文地址:http://www.cnblogs.com/shadowwalker9/p/5965979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!