Let's make this one less mysterious. For 140. Word Break II, the solution in this repository is mainly a trie solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: trie, DFS + memoization, dynamic programming.
The notes already sitting in the source point us in the right direction:
- DP
- TLE
- 31 / 36 test cases passed.
Guide
When?
Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are wordBreak, add, dfs.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- Substring checks are convenient but not free, so they are part of the real complexity story.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//DP
02//TLE
03//31 / 36 test cases passed.
04class Solution {
05public:
06 vector<string> wordBreak(string s, vector<string>& wordDict) {
07 int n = s.size();
08 if(n == 0) return vector<string>();
09
10 vector<vector<string>> segs(n);
11
12 for(int i = n-1; i >= 0; --i){
13 //check if s[i:] is itself a valid dict word
14 if(find(wordDict.begin(), wordDict.end(), s.substr(i)) != wordDict.end()){
15 segs[i].push_back(s.substr(i));
16 }
17 //split s[i] into two parts
18 /*
19 s[i:] : s[i:j-1] + s[j:]
20 s[i:j-1] is a valid dictionary word
21 s[j:] is composed by valid dictionary words
22 */
23 for(int j = n-1; j >= i+1; --j){
24 // cout << "j: " << j << ", segs[j].size(): " << segs[j].size() << endl;
25 // cout << "finding word: " << s.substr(i, j-i) << endl;
26 if(!segs[j].empty() &&
27 find(wordDict.begin(), wordDict.end(), s.substr(i, j-i)) != wordDict.end()){
28 for(string& prev_seg : segs[j]){
29 // cout << s.substr(i, j-i) << " + " << prev_seg << endl;
30 segs[i].push_back(s.substr(i, j-i) + " " + prev_seg);
31 }
32 }
33 }
34 }
35
36 // for(int i = 0; i < n; ++i){
37 // cout << "substr: " << s.substr(i) << endl;
38 // for(string& seg : segs[i]){
39 // cout << seg << endl;
40 // }
41 // }
42
43 return segs[0];
44 }
45};
46
47//DP + trie
48//TLE
49//31 / 36 test cases passed.
50class TrieNode {
51public:
52 vector<TrieNode*> children;
53 bool end;
54
55 TrieNode(){
56 children = vector<TrieNode*>(26, nullptr);
57 end = false;
58 }
59};
60
61class Trie {
62public:
63 TrieNode* root;
64
65 Trie(){
66 root = new TrieNode();
67 }
68
69 void add(string& word){
70 TrieNode* cur = root;
71 for(char c : word){
72 if(!cur->children[c-'a']){
73 cur->children[c-'a'] = new TrieNode();
74 }
75 cur = cur->children[c-'a'];
76 }
77 cur->end = true;
78 }
79
80 bool find(string word){
81 TrieNode* cur = root;
82 for(char c : word){
83 if(!cur->children[c-'a']){
84 return false;
85 }
86 cur = cur->children[c-'a'];
87 }
88 return cur->end;
89 }
90};
91
92class Solution {
93public:
94 vector<string> wordBreak(string s, vector<string>& wordDict) {
95 int n = s.size();
96 if(n == 0) return vector<string>();
97
98 Trie* trie = new Trie();
99
100 for(string& word : wordDict){
101 trie->add(word);
102 }
103
104 vector<vector<string>> segs(n);
105
106 for(int i = n-1; i >= 0; --i){
107 //check if s[i:] is itself a valid dict word
108 if(trie->find(s.substr(i))){
109 segs[i].push_back(s.substr(i));
110 }
111 //split s[i] into two parts
112 /*
113 s[i:] : s[i:j-1] + s[j:]
114 s[i:j-1] is a valid dictionary word
115 s[j:] is composed by valid dictionary words
116 */
117 for(int j = n-1; j >= i+1; --j){
118 // cout << "j: " << j << ", segs[j].size(): " << segs[j].size() << endl;
119 // cout << "finding word: " << s.substr(i, j-i) << endl;
120 if(!segs[j].empty() && trie->find(s.substr(i, j-i))){
121 for(string& prev_seg : segs[j]){
122 // cout << s.substr(i, j-i) << " + " << prev_seg << endl;
123 segs[i].push_back(s.substr(i, j-i) + " " + prev_seg);
124 }
125 }
126 }
127 }
128
129 // for(int i = 0; i < n; ++i){
130 // cout << "substr: " << s.substr(i) << endl;
131 // for(string& seg : segs[i]){
132 // cout << seg << endl;
133 // }
134 // }
135
136 return segs[0];
137 }
138};
139
140//DFS + memorization, each time move a "word" forward
141//https://leetcode.com/problems/word-break-ii/discuss/44167/My-concise-JAVA-solution-based-on-memorized-DFS
142//Runtime: 12 ms, faster than 93.80% of C++ online submissions for Word Break II.
143//Memory Usage: 10.1 MB, less than 84.03% of C++ online submissions for Word Break II.
144class Solution {
145public:
146 unordered_map<string, vector<string>> memo;
147
148 void dfs(string s, vector<string>& wordDict){
149 if(memo.find(s) != memo.end()){
150 return;
151 }
152
153 if(s.size() == 0){
154 memo[s] = {""};
155 return;
156 }
157
158 for(string& word : wordDict){
159 if(s.rfind(word, 0)==0){ //startswith
160 //split s into word + s.substr(word.size())
161 dfs(s.substr(word.size()), wordDict);
162 for(string& seg : memo[s.substr(word.size())]){
163 memo[s].push_back(word + ((!seg.empty()) ? " " : "") + seg);
164 }
165 }
166 }
167 };
168
169 vector<string> wordBreak(string s, vector<string>& wordDict) {
170 dfs(s, wordDict);
171
172 return memo[s];
173 }
174};
Cost