解题思路:
morris遍历+双指针
以先序遍历的方式遍历根节点的左子树,以“右子树根节点左子树”的方式遍历右子树
时间复杂度:O(n)
空间复杂度:O(1)
提交代码:
class Solution{
public List<String> wordBreak(String s, List<String> wordDict) {
boolean[] mark=new boolean[s.length()+1];
mark[s.length()]=true;
for(int i=s.length()-1;i>=0;i--) {
for(int j=i+1;j<=s.length();j++) {
String tmp=s.substring(i, j);
if(mark[j]&&wordDict.contains(tmp)) {
mark[i]=true;
break;
}
}
}
List<String> res=new ArrayList<>();
List<String> path=new ArrayList<>();
dfs(s,0,wordDict,mark,path,res);
return res;
}
private void dfs(String s,int p,List<String> wordDict,boolean[] mark,
List<String> path,List<String> res) {
if(p==s.length()) {
StringBuilder str=new StringBuilder();
for(String word: path) {
str.append(word);
str.append(" ");
}
str.deleteCharAt(str.length()-1);
res.add(str.toString());
}
if(!mark[p]) return;
for(int i=p+1;i<=s.length();i++) {
String left=s.substring(p, i);
if(!wordDict.contains(left)) continue;
path.add(left);
dfs(s,i,wordDict,mark,path,res);
path.remove(path.size()-1);
}
}
}
运行结果: