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

转载于:https://www.cnblogs.com/yalphait/p/10354954.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值