首页 > 代码库 > 045. Jump Game II

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