-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy path140_Word_Break_ii
More file actions
50 lines (44 loc) · 1.42 KB
/
Copy path140_Word_Break_ii
File metadata and controls
50 lines (44 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
Leetcode 140: Word Break ii
Detailed video explanation: https://youtu.be/9-grHHGUVls
========================================================
C++:
----
class Solution {
unordered_map<string, vector<string>> dp;
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
if(dp.find(s) != dp.end()) return dp[s];
vector<string> result;
for(string w : wordDict){
if(s.substr(0, w.length()) == w){
if(w.length() == s.length())
result.push_back(w);
else{
vector<string> tmp = wordBreak(s.substr(w.length()), wordDict);
for(string t : tmp)
result.push_back(w + " " + t);
}
}
}
dp[s] = result;
return result;
}
};
Python3:
--------
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
dp = {}
def word_break(s):
if s in dp: return dp[s]
result = []
for w in wordDict:
if s[:len(w)] == w:
if len(w) == len(s): result.append(w)
else:
tmp = word_break(s[len(w):])
for t in tmp:
result.append(w + " " + t)
dp[s] = result
return result
return word_break(s)