一个关键点在于:判断其中一部分如果在词典中,那么只要递归的判断剩下一部分即可
可以很快写出一个简单的搜索:
class Solution {
// 思路 前一部分是词典里的单词 那么将后一部分继续递归判断
private boolean helper(String s,int pos,HashSet<String> dict){
if(pos==s.length()){
return true;
}
for(int i=pos+1;i<=s.length();i++){
String pre=s.substring(pos,i);
if(dict.contains(pre)&&helper(s,i,dict)){
return true;
}
}
return false;
}
public boolean wordBreak(String s, List<String> wordDict) {
return helper(s,0,new HashSet<>(wordDict));
}
}
超时
原因很简单:

因为这里的重复计算是判断i开头的字符串是否breakable,所以这里可以对其做一个memo,去掉重复计算
class Solution {
// 思路 前一部分是词典里的单词 那么将后一部分继续递归判断
private Boolean[] Break;
private boolean helper(String s,int pos,HashSet<String> dict){
if(pos==s.length()){
return true;
}
if(Break[pos]!=null){
return Break[pos];
}
for(int i=pos+1;i<=s.length();i++){
String pre=s.substring(pos,i);
if(dict.contains(pre)&&helper(s,i,dict)){
Break[pos]=true;
return true;
}
}
Break[pos]=false;
return false;
}
public boolean wordBreak(String s, List<String> wordDict) {
Break=new Boolean[s.length()];
return helper(s,0,new HashSet<>(wordDict));
}
}

这篇博客探讨了如何使用动态规划优化解决LeetCode的Word Break问题,通过避免重复计算来提升效率。作者首先展示了基础的递归解决方案,然后引入了记忆化搜索以降低复杂性,从而解决了超时问题。
1632

被折叠的 条评论
为什么被折叠?



