1. 程式人生 > >19.2.7 [LeetCode 45] Jump Game II

19.2.7 [LeetCode 45] Jump Game II

public 很多 號稱 tor ++ 簡單 repr integer hellip

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