Skip to content

Commit 40c0615

Browse files
committed
添加(0139.单词拆分.md):增加Java回回溯+记忆化版本
1 parent 8ac7cdc commit 40c0615

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

problems/0139.单词拆分.md

Lines changed: 30 additions & 0 deletions
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:

0 commit comments

Comments
 (0)