Title description
https://leetcode-cn.com/problems/jump-game/
solution
Thinking about using dp to do it, why is our dp array defined?
- What are variables? Every jump, the position reached is different, and the number of steps that can be jumped at each position is also different. How do we define dp?
- Obviously we use dp to express the number of steps that can be jumped at each position, so we can only choose the position to reach, so dp[i] indicates whether the subscript from 0 to i can be reached
- Thinking about recursion, the current dp[i] depends on whether it can be reached from the previous position. We need to maintain a variable to represent the maximum subscript that can be reached at the moment. If the current subscript is within the maximum reachable subscript range Within (because you can skip 1 step), it is true, so update max
- The boundary is dp[0] = true;
- Write code
class Solution {
public boolean canJump(int[] nums) {
boolean []dp = new boolean[nums.length];//表示从0到下标i的是否可以到达
dp[0]=true;
int max = 0+nums[0];//当前能抵达的最大下标
for(int i=1;i<nums.length;i++){
if(max>=i){
dp[i] = true;
if(nums[i]+i>max)
max = nums[i]+i;//更新能抵达的最大下标
}
//else dp[i] = false;//不能抵达
}
return dp[nums.length-1];
}
}
According to the use of dp, the space complexity can be optimized:
class Solution {
public boolean canJump(int[] nums) {
//boolean []dp = new boolean[nums.length];//表示从0到下标i的是否可以到达
boolean res = true;//dp[0]等于true
int max = 0+nums[0];//当前能抵达的最大下标
for(int i=1;i<nums.length;i++){
if(max>=i){
res = true;
if(nums[i]+i>max)
max = nums[i]+i;//更新能抵达的最大下标
}else
res = false;
}
return res;
}
}
What if a greedy algorithm is used?
Conversion question: How far can I jump by passing the jumping rules in the question? If it can cross the last square, return true, otherwise return false.
So we can write the following greedy code:
int n = nums.length;
int farthest = 0;
for (int i = 0; i < n - 1; i++) {
// 不断计算能跳到的最远距离
farthest = max(farthest, i + nums[i]);
// 可能碰到了 0,卡住跳不动了
if (farthest <= i) return false;
}
return farthest >= n - 1;
Found that it is similar to the above code, can we think about the following difference between greedy and dynamic programming?