您的位置:首页 > 其它

[leetcode] 45. Jump Game II 解题报告

2015-10-28 13:44 369 查看
题目链接:https://leetcode.com/problems/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.

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.)

本题是一个动态规划题目,保存一个最大可到达的距离,并设置一个数组来保存到达每个位置最短的步数,最大可到达位置的状态转移方程为:

max(maxreach, A[i] + i);

即当前的位置加上当前最大可走的步数,如果本次更新了最大距离,则同样更新从上一个最大距离到这次最大距离之间位置的步数,要注意边界条件,就是最大到达距离超出了数组长度的时候要做一个判断。

代码如下:

class Solution {
public:
int jump(vector<int>& nums) {
vector<int> dp(nums.size(), INT_MAX);
dp[0] = 0;
int Max = 0, len = nums.size();
for(int i = 0; i < len; i++)
{
int tem = i+nums[i];
if(tem > Max)
{
for(int j = Max +1; j <= min(tem, len-1); j++) dp[j] = dp[i] + 1;
Max = tem;
if(Max >= nums.size()-1) return dp[nums.size()-1];
}
}
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: