Skip to content

Commit

Permalink
添加(0139.单词拆分.md):增加Java回回溯+记忆化版本
Browse files Browse the repository at this point in the history
  • Loading branch information
hutbzc committed Feb 1, 2022
1 parent 8ac7cdc commit 40c0615
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions problems/0139.单词拆分.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 40c0615

Please sign in to comment.