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"]
.
相比起word break I,这题不仅需要判断字符串能否成功被断句,还需要收集所有可能的断句。这种收集多种情况的问题一般用回溯完成。
但是回溯法遇到一个例子就超时了: s: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" dict里没有包含b的字符串。
所以依旧需要先dp判断能否断句,顺便对每一个位置用ArrayList<Integer>收集起当前词(如果在词典里)开始断的位置, 举个例子就是:
index 0 1 2 3 4 5 6 7 8 9 10
c a t s a n d d o g
dp 0 N N 0 0 N N 3 N N 7
4
回溯的树形结构即如此
代码如下:
1 public List<String> wordBreak(String s, Set<String> dict) { 2 List<String> ls = new ArrayList<String>(); 3 ArrayList<Integer>[] dp = new ArrayList[s.length()+1]; 4 dp[0] = new ArrayList<Integer>(); 5 dp[0].add(1); 6 for(int i=1;i<=s.length();i++) 7 for(int j=0;j<i;j++) 8 { 9 if(dp[j]!=null && dict.contains(s.substring(j,i))) 10 { 11 if(dp[i]==null) 12 dp[i] = new ArrayList<Integer>(); 13 dp[i].add(j); 14 } 15 } 16 if(dp[s.length()]==null) 17 return ls; 18 19 collect(ls,"",dp,s.length(),s); 20 return ls; 21 } 22 23 public void collect(List<String> ls, String path, ArrayList<Integer>[] dp, int index, String s) 24 { 25 for(int i=0;i<dp[index].size();i++) 26 { 27 String temp = s.substring(dp[index].get(i),index); 28 if(dp[index].get(i)==0) 29 ls.add(temp+path); 30 else 31 collect(ls," "+temp+path,dp,dp[index].get(i),s); 32 } 33 }
时间: 2024-10-13 03:04:23