题目概述
解题思路
这道题的题意是,告诉我们有条石子路,和从每个石子跳跃的最大距离,问我们抵达终点的最少要跳几次。
我一开始采用动态规划的方法,开个一维数组记录到每个石子需要的最少跳跃次数。
然后参考了大佬的博客,发现其实空间复杂度可以优化到O(1):
采用贪心的做法,先记录上一次跳跃的最远范围preLen,当前能跳到的最远距离为curLen(初始化时,上一次跳跃的距离为0,这一次的为nums[0]),然后计算下一次跳跃最远能到的距离是多少:
其实就是从preLen + 1开始遍历到curLen,找出这些新增的位置里面,最远可能到达的位置,用来更新curLen,同样要在更新curLen之前更新preLen。如果curLen超过了道路长度,表示当前可以跳到终点,则返回跳跃的次数。
方法性能
O(N)时间复杂度+O(1)空间复杂度:
示例代码
class Solution {
public:
int jump(vector<int>& nums) //dynamic programming
{
if(nums.size() == 1)
return 0;
int len = nums.size(), maxLen = 0;
vector<int>refer(len,0);
for(int i = 0; i < len; ++i)
{
for(int j = max(maxLen + 1, i + 1); j <= min(nums[i] + i, len - 1); ++j)
refer[j] = refer[i] + 1;
maxLen = max(maxLen, nums[i] + i);
}
return refer[len - 1];
}
};
class Solution {
public:
int jump(vector<int>& nums) //greedy algorithm
{
if(nums.size() == 1)
return 0;
int len = nums.size(), preLen = 0, curLen = nums[0], res = 1;
while(curLen < len - 1)
{
int temp = 0;
for(int i = preLen + 1; i <= curLen; ++i)
temp = max(temp, i + nums[i]);
preLen = curLen;
curLen = temp;
res++;
}
return res;
}
};