跳跃游戏II

题源:leetcode

链接:https://leetcode-cn.com/problems/jump-game-ii/

这次讨论两种解法,一个dp一个贪心

贪心的方法:

 1 class Solution {
 2 public:
 3     int jump(vector<int>& nums) {
 4         int maxPos = 0, n = nums.size(), end = 0, step = 0;
 5         for (int i = 0; i < n - 1; ++i) {
 6             if (maxPos >= i) {
 7                 maxPos = max(maxPos, i + nums[i]);
 8                 if (i == end) {
 9                     end = maxPos;
10                     ++step;
11                 }
12             }
13         }
14         return step;
15     }
16 };

dp的方法在C++上超时,但是也讲一下。dp[i] = min{dp[i],dp[j]+1}

 1 class Solution {
 2 public:
 3     int jump(vector<int>& nums) {
 4         int n = nums.size();
 5         vector<int> f(n, 0x3f3f3f3f);
 6         for (int i = 0; i < n; i++) {
 7             if (!i) f[i] = 0; // 处理边界
 8             else {
 9                 for (int j = 0; j < i; j++) { 
10                     if (j + nums[j] >= i) { // 只要前面的点能跳到i点就更新最小值
11                         f[i] = min(f[i], f[j] + 1);
12                     }
13                 }
14             }
15         }
16         return f[n - 1];
17     }
18 }
原文地址:https://www.cnblogs.com/hosheazhang/p/15094770.html