19.2.7 [LeetCode 45] Jump Game II

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
    Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note:

You can assume that you can always reach the last index.

题意

数组表示在编号位置处能跳的最大步数,问从0位置开始经历最少几步能正好到达终点

题解

一开始搞了个简单dp,极慢

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

bfs完全一样……

 1 class Solution {
 2 public:
 3     struct node {
 4         int posi, step;
 5         node(int x, int y) :posi(x), step(y) {}
 6     };
 7     int jump(vector<int>& nums) {
 8         queue<node>q;
 9         int n = nums.size();
10         vector<bool>visited(n, false);
11         q.push(node(0,0));
12         visited[0] = true;
13         while (!q.empty()) {
14             node now = q.front(); q.pop();
15             if (now.posi == n - 1)return now.step;
16             for (int i = now.posi + 1; i <= now.posi + nums[now.posi] && i < n; i++)
17                 if (!visited[i]) {
18                     visited[i] = true;
19                     q.push(node(i,now.step+1));
20                 }
21         }
22         return -1;
23     }
24 };
View Code

后来用了贪心还是慢,虽然已经快很多了

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

然后评论区试了很多号称beat 99%的题解,都差不多是上面那个速度……

猜你喜欢

转载自www.cnblogs.com/yalphait/p/10354954.html