1
+ /*
2
+ Author: Andy, nkuwjg@gmail.com
3
+ Date: Jan 29, 2015
4
+ Problem: Word Break II
5
+ Difficulty: Easy
6
+ Source: http://oj.leetcode.com/problems/word-break-ii/
7
+ Notes:
8
+ Given a string s and a dictionary of words dict, add spaces in s to
9
+ construct a sentence where each word is a valid dictionary word.
10
+ Return all such possible sentences.
11
+ For example, given
12
+ s = "catsanddog",
13
+ dict = ["cat", "cats", "and", "sand", "dog"].
14
+ A solution is ["cats and dog", "cat sand dog"].
15
+
16
+ Solution: check before constructing the sentences.
17
+ */
18
+
19
+ public class Solution {
20
+ public List <String > wordBreak (String s , Set <String > dict ) {
21
+ List <String > res = new ArrayList <String >();
22
+ int n = s .length ();
23
+ boolean [] canBreak = new boolean [n +1 ];
24
+ canBreak [n ] = true ;
25
+ for (int i = n - 1 ; i >= 0 ; --i ) {
26
+ for (int j = i ; j < n ; ++j ) {
27
+ if (dict .contains (s .substring (i ,j +1 )) && canBreak [j +1 ]) {
28
+ canBreak [i ] = true ;
29
+ break ;
30
+ }
31
+ }
32
+ }
33
+ if (canBreak [0 ] == false ) return res ;
34
+ wordBreakRe (s , dict , "" , 0 , res );
35
+ return res ;
36
+ }
37
+ public void wordBreakRe (String s , Set <String > dict , String path , int start , List <String > res ) {
38
+ if (start == s .length ()) {
39
+ res .add (path );
40
+ return ;
41
+ }
42
+ if (path .length () != 0 ) path = path + " " ;
43
+ for (int i = start ; i < s .length (); ++i ) {
44
+ String word = s .substring (start , i + 1 );
45
+ if (dict .contains (word ) == false ) continue ;
46
+ wordBreakRe (s , dict , path + word , i + 1 , res );
47
+ }
48
+ }
49
+ }
0 commit comments