Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d285d3d

Browse files
更改了回溯+记忆的逻辑
经过提交验证,其实memo[startIndex] = 1的这个逻辑根本没有用到,因为如果返回true,那么会如同dfs一样直接返回,不会再进行下一步的backtracking搜索,本题的记忆法核心是令memo[startIndex]置为-1,来避免从相同的startIndex开始拆分,导致程序进行大量重复运算,这应该也是本题剪枝方法的核心。
1 parent dd74213 commit d285d3d

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

‎problems/0139.单词拆分.md‎

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -251,30 +251,34 @@ class Solution {
251251

252252
// 回溯法+记忆化
253253
class Solution {
254+
private Set<String> set;
255+
private int[] memo;
254256
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);
257+
memo = new int[s.length()];
258+
set = new HashSet<>(wordDict);
259+
return backtracking(s, 0);
258260
}
259-
260-
public boolean backTrack(String s, Set<String>wordDictSet, int startIndex, int[] memory) {
261-
// 结束条件
262-
if (startIndex >= s.length()) {
261+
262+
public boolean backtracking(String s, int startIndex) {
263+
// System.out.println(startIndex);
264+
if (startIndex == s.length()) {
263265
return true;
264266
}
265-
if (memory[startIndex] != 0) {
266-
// 此处认为:memory[i] = 1 表示可以拼出i 及以后的字符子串, memory[i] = -1 表示不能
267-
return memory[startIndex] == 1 ? true : false;
267+
if (memo[startIndex] == -1) {
268+
return false;
268269
}
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-
returntrue;
270+
271+
for (int i = startIndex; i < s.length(); i++) {
272+
String sub = s.substring(startIndex, i + 1);
273+
// 拆分出来的单词无法匹配
274+
if (!set.contains(sub)) {
275+
continue;
275276
}
277+
boolean res = backtracking(s, i + 1);
278+
if (res) return true;
276279
}
277-
memory[startIndex] = -1;
280+
// 这里是关键,找遍了startIndex~s.length()也没能完全匹配,标记从startIndex开始不能找到
281+
memo[startIndex] = -1;
278282
return false;
279283
}
280284
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /