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

Note:
You can assume that you can always reach the last index. (Hard)

分析:

第一眼看完题目感觉用动态规划肯定能解,但是感觉就是有很多重复计算在里面...因为题目只问了个最少步数。

果然写出来之后华丽超时,但是代码还是记录一下吧

 class Solution {
public:
int jump(vector<int>& nums) {
int dp[nums.size()];
for (int i = ; i < nums.size(); ++i) {
dp[i] = 0x7FFFFFFF;
}
dp[] = ;
for (int i = ; i < nums.size(); ++i) {
for (int j = ; j < i; ++j) {
if (j + nums[j] >= i) {
dp[i] = min(dp[i], dp[j] + );
}
}
}
return dp[nums.size() - ];
}
};

优化考虑类似BFS的想法,维护一个步数的范围和一个能走到的最远距离。

算法就是遍历一遍数组,到每个位置的时候,更新他能到达的最远距离end,如果一旦超过nums.size() - 1,就返回step + 1;

curEnd维护以当前步数能到达的最远范围,所以当i > curEnd时,step++,并且将curEnd更新为end。

代码:

 class Solution {
public:
int jump(vector<int>& nums) {
if (nums.size() == ) {
return ;
}
int step = , end = , curEnd = ;
for (int i = ; i < nums.size(); ++i) {
if (i > curEnd) {
step++;
curEnd = end;
}
end = max(end, nums[i] + i);
if (end >= nums.size() - ) {
return step + ;
}
}
return -;
}
};
 
上一篇:SPREAD_NET6


下一篇:配置JAVA的环境变量