140. 单词拆分 II
Java错误代码:不该回溯数组的,回溯数组是以固定顺序来的,应该回溯字符串!
class Solution {
StringBuilder sb;
List<String> list;
List<String> tmp;
private String getString() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < tmp.size(); i++) {
str.append(tmp.get(i));
}
return str.toString();
}
private String getString1() {
StringBuilder str = new StringBuilder();
for (int i = 0; i < tmp.size() - 1; i++) {
str.append(tmp.get(i));
str.append(" ");
}
str.append(tmp.get(tmp.size() - 1));
return str.toString();
}
private void dfs(int pos, String str, String s, List<String> wordDict) {
if (s.equals(str)) {
list.add(getString1());
}
for (int i = pos; i < wordDict.size(); ++i) {
tmp.add(wordDict.get(i)); // 艹 写了半天发现是以任意顺序
String s1 = getString();
if (s1.length() <= s.length() && s.startsWith(s1)) {
dfs(i + 1, s1, s, wordDict);
}
tmp.remove(tmp.size() - 1);
}
}
public List<String> wordBreak(String s, List<String> wordDict) {
sb = new StringBuilder();
list = new ArrayList<>();
tmp = new ArrayList<>();
dfs(0, "", s, wordDict);
return list;
}
}