1
+ ///
2
+ /// Problem: Word Break II
3
+ ///
4
+ /// Given a string s and a dictionary of strings wordDict, add spaces in s to construct a
5
+ /// sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
6
+ ///
7
+ /// Note that the same word in the dictionary may be reused multiple times in the segmentation.
8
+ ///
9
+ /// Example 1:
10
+ /// Input: s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"]
11
+ /// Output: ["cats and dog","cat sand dog"]
12
+ ///
13
+ /// Example 2:
14
+ /// Input: s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"]
15
+ /// Output: ["pine apple pen apple","pineapple pen apple","pine applepen apple"]
16
+ ///
17
+ /// Example 3:
18
+ /// Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
19
+ /// Output: []
20
+ ///
21
+ /// Constraints:
22
+ /// 1 <= s.length <= 20
23
+ /// 1 <= wordDict.length <= 1000
24
+ /// 1 <= wordDict[i].length <= 10
25
+ /// s and wordDict[i] consist of only lowercase English letters.
26
+ /// All the strings of wordDict are unique.
27
+ ///
28
+
29
+ // # Solution
30
+ // Time complexity: O(n * 2^n)
31
+ // Space complexity: O(n * 2^n)
32
+
33
+ use std:: collections:: { HashSet , HashMap } ;
34
+
35
+ impl Solution {
36
+ pub fn word_break ( s : String , word_dict : Vec < String > ) -> Vec < String > {
37
+ let word_set: HashSet < String > = word_dict. into_iter ( ) . collect ( ) ;
38
+ let mut memo: HashMap < usize , Vec < String > > = HashMap :: new ( ) ;
39
+
40
+ Self :: dfs ( & s, 0 , & word_set, & mut memo)
41
+ }
42
+
43
+ fn dfs ( s : & str , start : usize , word_set : & HashSet < String > , memo : & mut HashMap < usize , Vec < String > > ) -> Vec < String > {
44
+ if let Some ( result) = memo. get ( & start) {
45
+ return result. clone ( ) ;
46
+ }
47
+
48
+ let mut result = Vec :: new ( ) ;
49
+
50
+ if start == s. len ( ) {
51
+ result. push ( String :: new ( ) ) ;
52
+ return result;
53
+ }
54
+
55
+ for end in start + 1 ..=s. len ( ) {
56
+ let prefix = & s[ start..end] ;
57
+
58
+ if word_set. contains ( prefix) {
59
+ let sub_segments = Self :: dfs ( s, end, word_set, memo) ;
60
+
61
+ for segment in sub_segments {
62
+ if segment. is_empty ( ) {
63
+ result. push ( prefix. to_string ( ) ) ;
64
+ } else {
65
+ result. push ( format ! ( "{} {}" , prefix, segment) ) ;
66
+ }
67
+ }
68
+ }
69
+ }
70
+
71
+ memo. insert ( start, result. clone ( ) ) ;
72
+ result
73
+ }
74
+ }
0 commit comments