Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
***s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].*
A solution is [“cats and dog”, “cat sand dog”].
这道题是 DFS + dynamic programming,word break I里面是用boolean数组来存储字符串在某一个位置是否能被分割。 那么word break II就是用一个ArrayList的dp[] 数组来存储 String在某一个位置可以往前数,可以构成多少个在Dict里面的单词
public class Solution {
public List<String> wordBreak(String s, Set<String> wordDict) {
ArrayList<String> dp[] = new ArrayList[s.length()+1];
dp[0] = new ArrayList<String>();
for(int i=0;i<s.length()+1;i++){
if( dp[i] == null )
continue;
for(String a:wordDict){
int end = a.length()+i;
if(end>s.length()) continue;
if(s.substring(i,end).equals(a)){
if(dp[end]==null) {dp[end] = new ArrayList<String>();}
dp[end].add(a);
}
}
}
List<String> result = new ArrayList<String>();
if(dp[s.length()]==null) return result;
ArrayList<String> temp = new ArrayList<String>();
dfs(dp,result,s.length(),temp);
return result;
}
public void dfs(ArrayList<String>[] dp,List<String> result,int end,ArrayList<String> temp){
if(end<=0){
String path = temp.get(temp.size()-1);
for(int i=temp.size()-2; i>=0; i--){
path += " " + temp.get(i) ;
}
result.add(path);
return;
}
for(String a:dp[end]){
// System.out.println(dp[end]);
temp.add(a);
System.out.println(temp);
dfs(dp,result,end-a.length(),temp);
temp.remove(temp.size()-1);
}
}
}
原来没有仔细的想过dfs里面执行代码的过程,比如test case是
***s = “catsanddog”,
dict = [“cat”, “cats”, “and”, “sand”, “dog”].*
Your stdout:
[dog]
[dog, sand]
[dog, sand, cat]
[dog, and]
[dog, and, cats]
当temp = [dog, sand, cat],代码执行到 temp.remove(temp.size()-1)的时候,应该怎么执行,这个时候应该是进入for循环里面,看看for循环还能不能继续往下面执行了,如果不能继续往下执行的话,这个dfs函数就执行完毕,执行父辈的dfs函数,继续remove单词 sand 这个和subset里面的dfs执行是一样一样的