Given A string s and a Dictionary of words dict, add spaces in s to construct a sentence where Each of the 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"]
.
139 extension Questions, all results are required.
1, recursion, still timed out.
Public classSolution {string[] result; List List; PublicList<string> Wordbreak (String s, set<string>worddict) { intLen = S.length (), MaxLen = 0; Result=NewString[len]; List=NewArraylist<string>(); for(String str:worddict) {maxlen=Math.max (Maxlen,str.length ()); } helper (S,0,worddict,maxlen,0); returnlist; } Public voidHelper (String s,intPos,set<string> Worddict,intMaxLen,intcount) { if(pos = =s.length ()) {String str= Result[0]; for(inti = 1; i<count-1;i++) {str=str+ "" +Result[i]; } if(Count > 1) Str= str+ "" +result[count-1]; List.add (str); } intFlag = 0; for(inti = Pos;pos-i<maxlen && i<s.length (); i++){ if(Worddict.contains (S.substring (pos,i+1)) {Result[count]= S.substring (pos,i+1); Helper (S,i+1,worddict,maxlen,count+1); Flag= 1; } } }}
2, join in advance to determine whether there is an answer (that is, the conclusion of the previous question) on it.
Public classSolution {string[] result; List List; PublicList<string> Wordbreak (String s, set<string>worddict) { intLen = S.length (), MaxLen = 0; Result=NewString[len]; List=NewArraylist<string>(); for(String str:worddict) {maxlen=Math.max (Maxlen,str.length ()); } Boolean[] DP =New Boolean[Len]; for(inti = 0; i<len;i++){ for(intj = i;j>=0 && i-j<maxlen;j-- ){ if(j = = 0 | | dp[j-1] = =true) && Worddict.contains (s.substring (j,i+1)) {Dp[i]=true; Break; } } } if(Dp[len-1] = =false) returnlist; Helper (S,0,worddict,maxlen,0); returnlist; } Public voidHelper (String s,intPos,set<string> Worddict,intMaxLen,intcount) { if(pos = =s.length ()) {String str= Result[0]; for(inti = 1; i<count-1;i++) {str=str+ "" +Result[i]; } if(Count > 1) Str= str+ "" +result[count-1]; List.add (str); } intFlag = 0; for(inti = Pos;pos-i<maxlen && i<s.length (); i++){ if(Worddict.contains (S.substring (pos,i+1)) {Result[count]= S.substring (pos,i+1); Helper (S,i+1,worddict,maxlen,count+1); Flag= 1; } } }}
Leetcode 140. Word Break II-----java