码迷,mamicode.com
首页 > 其他好文 > 详细

19.2.7 [LeetCode 45] Jump Game II

时间:2019-02-07 17:51:36      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:简单   maximum   beat   eps   ini   push   res   output   leetcode   

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%的题解,都差不多是上面那个速度……

19.2.7 [LeetCode 45] Jump Game II

标签:简单   maximum   beat   eps   ini   push   res   output   leetcode   

原文地址:https://www.cnblogs.com/yalphait/p/10354954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!