您的位置:首页 > 其它

LeetCode 45. Jump Game II(跳跃游戏Ⅱ)

2018-03-20 15:29 337 查看
题目描述:    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.    For example: given array A = 
[2,3,1,1,4]
    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.分析:    题意:给定一个非负整型数组A,大小为n。A[i]表示从i位置出发的最大跳跃步数。求从0点出发,到达n - 1点的最小步数。    思路:这道题可以用两种思路来考虑:① 动态规划;② 贪心。虽然这道题采用动态规划会超时(91 / 92 test cases passed),我还是打算一起说明一下。    ① 动态规划:我们建立数组dp,初始化为INT_MAX(其中dp[0] = 0),dp[i]表示从起点到达i点的最小步数,可以得到状态转换方程:    dp[i + j] = min{dp[i + j], dp[i] + 1}, j = {1, 2, 3, ... , nums[i]}代码(超时):#include <bits/stdc++.h>using namespace std;class Solution {public:int jump(vector<int>& nums) {int n = nums.size();if(n <= 1){return 0;}vector<int> dp(n, INT_MAX);// initdp[0] = 0;// dpfor(int i = 0; i < n - 1; i++){for(int j = 1; j <= nums[i]; j++){if(i + j <= n - 1){dp[i + j] = min(dp[i + j], dp[i] + 1);}}}return dp[n - 1];}};    ② 贪心:对于每一个位置i,我们用pre表示i之前能够达到的最远位置,cur表示包含从i出发的情况,此时能够到达的最远位置。如果 i == pre,说明当前从i跳跃要重新计算步数(因为i之前最远恰好能够到达i),同时更新pre = cur(因为从i出发已经统计步数)。顺序遍历0→n - 2(因为题意默认存在解,从i - 1出发不需要考虑),最后返回答案。代码:#include <bits/stdc++.h>using namespace std;// BFS + Greedyclass Solution {public:int jump(vector<int>& nums) {int n = nums.size();// Exceptional Case:if(n == 0){return 0;}int preMaxEnd = 0, curMaxEnd = 0;int ans = 0;for(int i = 0; i <= n - 2; i++){curMaxEnd = max(curMaxEnd, i + nums[i]);if(i == preMaxEnd){ans++;preMaxEnd = curMaxEnd;}}return ans;}};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C LeetCode BFS Greedy