Skip to content

Commit 292942d

Browse files
Merge pull request youngyangyang04#1071 from hutbzc/master
添加(0139.单词拆分.md):增加Java回溯+记忆化版本;添加(0045.跳跃游戏II.md):补充Java版本2;修改(0376.摆动序列.md):修改了逻辑小错误
2 parents 742ccc4 + 5a2ff02 commit 292942d

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

Diff for: problems/0045.跳跃游戏II.md

+24
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ public:
142142

143143
### Java
144144
```Java
145+
// 版本一
145146
class Solution {
146147
public int jump(int[] nums) {
147148
if (nums == null || nums.length == 0 || nums.length == 1) {
@@ -172,7 +173,30 @@ class Solution {
172173
}
173174
```
174175

176+
```java
177+
// 版本二
178+
class Solution {
179+
public int jump(int[] nums) {
180+
int result = 0;
181+
// 当前覆盖的最远距离下标
182+
int end = 0;
183+
// 下一步覆盖的最远距离下标
184+
int temp = 0;
185+
for (int i = 0; i <= end && end < nums.length - 1; ++i) {
186+
temp = Math.max(temp, i + nums[i]);
187+
// 可达位置的改变次数就是跳跃次数
188+
if (i == end) {
189+
end = temp;
190+
result++;
191+
}
192+
}
193+
return result;
194+
}
195+
}
196+
```
197+
175198
### Python
199+
176200
```python
177201
class Solution:
178202
def jump(self, nums: List[int]) -> int:

Diff for: problems/0139.单词拆分.md

+30
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,36 @@ class Solution {
248248
return valid[s.length()];
249249
}
250250
}
251+
252+
// 回溯法+记忆化
253+
class Solution {
254+
public boolean wordBreak(String s, List<String> wordDict) {
255+
Set<String> wordDictSet = new HashSet(wordDict);
256+
int[] memory = new int[s.length()];
257+
return backTrack(s, wordDictSet, 0, memory);
258+
}
259+
260+
public boolean backTrack(String s, Set<String> wordDictSet, int startIndex, int[] memory) {
261+
// 结束条件
262+
if (startIndex >= s.length()) {
263+
return true;
264+
}
265+
if (memory[startIndex] != 0) {
266+
// 此处认为:memory[i] = 1 表示可以拼出i 及以后的字符子串, memory[i] = -1 表示不能
267+
return memory[startIndex] == 1 ? true : false;
268+
}
269+
for (int i = startIndex; i < s.length(); ++i) {
270+
// 处理 递归 回溯 循环不变量:[startIndex, i + 1)
271+
String word = s.substring(startIndex, i + 1);
272+
if (wordDictSet.contains(word) && backTrack(s, wordDictSet, i + 1, memory)) {
273+
memory[startIndex] = 1;
274+
return true;
275+
}
276+
}
277+
memory[startIndex] = -1;
278+
return false;
279+
}
280+
}
251281
```
252282

253283
Python:

Diff for: problems/0376.摆动序列.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ public:
174174
```Java
175175
class Solution {
176176
public int wiggleMaxLength(int[] nums) {
177-
if (nums == null || nums.length <= 1) {
177+
if (nums.length <= 1) {
178178
return nums.length;
179179
}
180180
//当前差值

0 commit comments

Comments
 (0)