mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Merge pull request #1146 from Younglesszzz/master
更新LC139 单词拆分 回溯+记忆的逻辑 java
This commit is contained in:
@ -250,30 +250,34 @@ class Solution {
|
|||||||
|
|
||||||
// 回溯法+记忆化
|
// 回溯法+记忆化
|
||||||
class Solution {
|
class Solution {
|
||||||
|
private Set<String> set;
|
||||||
|
private int[] memo;
|
||||||
public boolean wordBreak(String s, List<String> wordDict) {
|
public boolean wordBreak(String s, List<String> wordDict) {
|
||||||
Set<String> wordDictSet = new HashSet(wordDict);
|
memo = new int[s.length()];
|
||||||
int[] memory = new int[s.length()];
|
set = new HashSet<>(wordDict);
|
||||||
return backTrack(s, wordDictSet, 0, memory);
|
return backtracking(s, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean backTrack(String s, Set<String> wordDictSet, int startIndex, int[] memory) {
|
public boolean backtracking(String s, int startIndex) {
|
||||||
// 结束条件
|
// System.out.println(startIndex);
|
||||||
if (startIndex >= s.length()) {
|
if (startIndex == s.length()) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (memory[startIndex] != 0) {
|
if (memo[startIndex] == -1) {
|
||||||
// 此处认为:memory[i] = 1 表示可以拼出i 及以后的字符子串, memory[i] = -1 表示不能
|
return false;
|
||||||
return memory[startIndex] == 1 ? true : false;
|
|
||||||
}
|
}
|
||||||
for (int i = startIndex; i < s.length(); ++i) {
|
|
||||||
// 处理 递归 回溯 循环不变量:[startIndex, i + 1)
|
for (int i = startIndex; i < s.length(); i++) {
|
||||||
String word = s.substring(startIndex, i + 1);
|
String sub = s.substring(startIndex, i + 1);
|
||||||
if (wordDictSet.contains(word) && backTrack(s, wordDictSet, i + 1, memory)) {
|
// 拆分出来的单词无法匹配
|
||||||
memory[startIndex] = 1;
|
if (!set.contains(sub)) {
|
||||||
return true;
|
continue;
|
||||||
}
|
}
|
||||||
|
boolean res = backtracking(s, i + 1);
|
||||||
|
if (res) return true;
|
||||||
}
|
}
|
||||||
memory[startIndex] = -1;
|
// 这里是关键,找遍了startIndex~s.length()也没能完全匹配,标记从startIndex开始不能找到
|
||||||
|
memo[startIndex] = -1;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user