Skip to content

Commit

Permalink
Update 55 跳跃游戏.md
Browse files Browse the repository at this point in the history
  • Loading branch information
upangka committed Oct 5, 2023
1 parent 00efa2f commit 7814df7
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions docs/Algorithm/55 跳跃游戏.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,34 @@ public class Solution {
// false
```



## 动态规划

这是个非常明显的“多阶段决策最优解”类型的问题,每达到一个数组的元素,都是一个决策,这个决策的最优解就是我们当前阶段我们能够跳跃的最大值是多少

很明显,按照我们求解动态规划问题的步骤和思想,首先设定一个dp数组,`dp[i]`表示在下标i处能够跳跃的最大值

- 对于dp[i],它等于`dp[i-1]`跳一格到达i处后剩余的步数和`nums[i]`的两者中的最大值。因此状态转移方程为:`dp[i]=max(dp[i-1]-1,nums[i])`

初始化条件就是`dp[0]=nums[0]`

在每次循环开始,我们判断`dp[i-1]`是否等于0,若是,则不可能到达下标i处,因此直接返回false。循环结束后返回true

```java
public class Solution {
public boolean canJump(int[] nums) {
// dp[i] 表示当前位置的最大步数
int[] dp = new int[nums.length];
dp[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
if(dp[i - 1] == 0){
return false;
}
dp[i] = Math.max(dp[i-1]-1,nums[i]);
}
return true;
}
}
```

0 comments on commit 7814df7

Please sign in to comment.