首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。