原题链接在这里:https://leetcode.com/problems/word-break-ii/
本题是Word Break的进阶题,要返回所有wordbreak的结果。
本题参照了这篇帖子:http://www.cnblogs.com/springfor/p/3877056.html
首先更具isWordBreak判断是否能拆,若能拆看从头到尾走,找到了一个wordDict里包含的字符串,然后从后一个点就用递归方法调用helper, 递归的stop condition是能走到正好结尾,否则跳出for loop, res不变。
Note: helper的for loop中若wordDict包含当前sb.toString(), 应该建立一个新的string, newString, 它相当于一个copy, 因为回朔到这点时,str应该回到最开始的时候,若不用这个copy当回到这点时str可能已经不是最开始的状态。
AC Java:
public class Solution {
public List<String> wordBreak(String s, Set<String> wordDict) {
List<String> res = new ArrayList<String>();
if(s == null || s.length() == 0){
return res;
}
if(isWordBreak(s,wordDict)){
helper(s, wordDict, 0, "",res);
}
return res;
}
private void helper(String s, Set<String> wordDict,int start, String str, List<String> res){
if(start == s.length()){
res.add(str);
return;
}
StringBuilder sb = new StringBuilder();
for(int i = start; i< s.length(); i++){
sb.append(s.charAt(i));
if(wordDict.contains(sb.toString())){
String newString = new String(); //error
if(str.length() == 0){
newString = sb.toString();
}else{
newString = str + " " + sb.toString();
}
helper(s,wordDict,i+1,newString,res);
}
}
}
private boolean isWordBreak(String s, Set<String> wordDict){
if(s == null || s.length() ==0){
return true;
}
boolean [] dp = new boolean[s.length()+1];
dp[0] = true;
for(int i = 0; i < s.length(); i++){
StringBuilder sb= new StringBuilder(s.substring(0,i+1));
for(int j = 0; j<=i; j++){
if(dp[j] && wordDict.contains(sb.toString())){
dp[i+1] = true;
break;
}
sb.deleteCharAt(0);
}
}
return dp[s.length()];
}
}