045. Jump Game II

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了045. Jump Game II相关的知识,希望对你有一定的参考价值。

方法一:遍历所有可能的情况,复杂度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的主要内容,如果未能解决你的问题,请参考以下文章

Jump Game II

55 Jump Game i && 45 Jump Game ii

45. Jump Game II

55. 45. Jump Game II *HARD*

LintCode : Jump Game II

45. Jump Game II