-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path472.cpp
45 lines (39 loc) · 974 Bytes
/
472.cpp
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
class Solution {
public:
bool dfs(string &str, unordered_map<string, int> &mp, int idx){
if(idx == str.size()){
return true;
}
string tmp = "";
for(int i = idx; i < str.size(); i++){
tmp += str[i];
if(mp[tmp] > 0 && dfs(str, mp, i + 1)){
return true;
}
}
return false;
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_map<string, int> mp;
for(auto str: words){
mp[str]++;
}
vector<string> Ans;
for(auto str: words){
mp[str]--;
if(dfs(str, mp, 0)){
Ans.push_back(str);
}
mp[str]++;
}
return Ans;
}
};
/*
Time complexity:
- size of words = N
- size of word = M
- To generate all substring of a string = M^3
- So total time complexity = O(N * m^3)
Space complexity: O(N*M)
*/