
思路一: brute force + backtracking。把所有的跳法都来一遍,然后选出跳动最少的那个跳法。但是很可惜tle。还是展示下代码,代码基本和jumpgame1一模一样,就是加了个计数器,计算跳动次数。
class Solution {
public int jump(int[] nums) {
int len = nums.length;
int res = Integer.MAX_VALUE;
int[] memo = new int[len];
Arrays.fill(memo,-1);
if(len == 1) return 0;
for(int i = 0; i < len - 1; i++){
if(nums[i] >= len - 1 - i){
int subRes = 0;
if(memo[i] == -1){
subRes = jump(Arrays.copyOfRange(nums,0,i + 1)) + 1;
memo[i] = subRes - 1;
}else{
subRes = memo[i] + 1;
}
res = Math.min(res,subRes);
}
}
return res;
}
}
思路二: greedy。对于贪心算法我一直都很不熟悉,这题其实也有想到要用贪心算法来做,但是因为没接触过什么经典的贪心算法题目,所以我也只是想想,之后要找时间专门了解一下贪心算法。简单说一下贪心算法运用在这道题的思路吧:
这就是这题的基本思路。具体解释我建议参考lc解释,解答大哥解释的还是挺清晰的,这边直接上代码:
class Solution {
public int jump(int[] nums) {
int len = nums.length;
if(len < 2) return 0;
int max_pos = nums[0];
int max_step = nums[0];
int jump = 1;
for(int i = 1; i < len; ++i){
if(max_step < i){
// greedy
max_step = max_pos;
jump++;
}
max_pos = Math.max(max_pos,nums[i] + i);
}
return jump;
}
}
总结:
- 这题还有dp做法,感觉应该是从jumpgame1那边过来的思路,复盘时候建议自己思考一下dp做法。
本文探讨了跳跃游戏II的两种解法,包括bruteforce+backtracking和greedy算法,详细分析了每种方法的实现思路及代码示例。
1310

被折叠的 条评论
为什么被折叠?



