mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Merge pull request #1071 from hutbzc/master
添加(0139.单词拆分.md):增加Java回溯+记忆化版本;添加(0045.跳跃游戏II.md):补充Java版本2;修改(0376.摆动序列.md):修改了逻辑小错误
This commit is contained in:
@ -142,6 +142,7 @@ public:
|
||||
|
||||
### Java
|
||||
```Java
|
||||
// 版本一
|
||||
class Solution {
|
||||
public int jump(int[] nums) {
|
||||
if (nums == null || nums.length == 0 || nums.length == 1) {
|
||||
@ -172,7 +173,30 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
// 版本二
|
||||
class Solution {
|
||||
public int jump(int[] nums) {
|
||||
int result = 0;
|
||||
// 当前覆盖的最远距离下标
|
||||
int end = 0;
|
||||
// 下一步覆盖的最远距离下标
|
||||
int temp = 0;
|
||||
for (int i = 0; i <= end && end < nums.length - 1; ++i) {
|
||||
temp = Math.max(temp, i + nums[i]);
|
||||
// 可达位置的改变次数就是跳跃次数
|
||||
if (i == end) {
|
||||
end = temp;
|
||||
result++;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def jump(self, nums: List[int]) -> int:
|
||||
|
@ -248,6 +248,36 @@ class Solution {
|
||||
return valid[s.length()];
|
||||
}
|
||||
}
|
||||
|
||||
// 回溯法+记忆化
|
||||
class Solution {
|
||||
public boolean wordBreak(String s, List<String> wordDict) {
|
||||
Set<String> wordDictSet = new HashSet(wordDict);
|
||||
int[] memory = new int[s.length()];
|
||||
return backTrack(s, wordDictSet, 0, memory);
|
||||
}
|
||||
|
||||
public boolean backTrack(String s, Set<String> wordDictSet, int startIndex, int[] memory) {
|
||||
// 结束条件
|
||||
if (startIndex >= s.length()) {
|
||||
return true;
|
||||
}
|
||||
if (memory[startIndex] != 0) {
|
||||
// 此处认为:memory[i] = 1 表示可以拼出i 及以后的字符子串, memory[i] = -1 表示不能
|
||||
return memory[startIndex] == 1 ? true : false;
|
||||
}
|
||||
for (int i = startIndex; i < s.length(); ++i) {
|
||||
// 处理 递归 回溯 循环不变量:[startIndex, i + 1)
|
||||
String word = s.substring(startIndex, i + 1);
|
||||
if (wordDictSet.contains(word) && backTrack(s, wordDictSet, i + 1, memory)) {
|
||||
memory[startIndex] = 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
memory[startIndex] = -1;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
|
@ -174,7 +174,7 @@ public:
|
||||
```Java
|
||||
class Solution {
|
||||
public int wiggleMaxLength(int[] nums) {
|
||||
if (nums == null || nums.length <= 1) {
|
||||
if (nums.length <= 1) {
|
||||
return nums.length;
|
||||
}
|
||||
//当前差值
|
||||
|
Reference in New Issue
Block a user