-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathNumber of Ways to Form a Target String Given a Dictionary.cpp
83 lines (68 loc) · 2.6 KB
/
Number of Ways to Form a Target String Given a Dictionary.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//Recursion
class Solution {
long getWords(vector<string>&words,string &target,int i,int j){
if(j == target.size())return 1;
if(i== words[0].size() || words[0].size() - i < target.size() - j)return 0;
long count = 0;
for(int idx = 0; idx < words.size(); idx++){
if(words[idx][i] == target[j]){
count += getWords(words, target, i + 1, j + 1)%1000000007;
}
}
count += getWords(words, target, i + 1, j)%1000000007;
return count%1000000007;
}
public:
int numWays(vector<string>& words, string target) {
return getWords(words, target, 0, 0);
}
};
//memoization but still (85/89)
class Solution {
vector<vector<int>>dp;
long getWords(vector<string>&words,string &target,int i,int j){
if(j == target.size())return 1;
if(i== words[0].size() || words[0].size() - i < target.size() - j)return 0;
if(dp[i][j] != -1)return dp[i][j];
long count = 0;
for(int idx = 0; idx < words.size(); idx++){
if(words[idx][i] == target[j]){
count += getWords(words, target, i + 1, j + 1)%1000000007;
}
}
count += getWords(words, target, i + 1, j)%1000000007;
return dp[i][j] = count%1000000007;
}
public:
int numWays(vector<string>& words, string target) {
dp.resize(words[0].size(), vector<int>(target.size(), -1));
return getWords(words, target, 0, 0);
}
};
// memoization + optimization (by pre calculating frequency)
class Solution {
vector<vector<int>>dp;
vector<vector<int>>freq;
long getWords(vector<string>&words, string &target, int i, int j){
if(j == target.size())return 1;
if(i == words[0].size() || words[0].size() - i < target.size() - j) return 0;
if(dp[i][j] != -1)return dp[i][j];
long count = 0;
int curPos = target[j] - 'a';
count += getWords(words, target, i + 1, j);
count += freq[i][curPos] * getWords(words, target, i + 1, j + 1);
return dp[i][j] = count % 1000000007;
}
public:
int numWays(vector<string>& words, string target) {
dp.resize(words[0].size(), vector<int>(target.size(), -1));
freq.resize(words[0].size(), vector<int>(26, 0));
for(int i=0; i<words.size(); i++){
for(int j = 0; j < words[0].size(); j++){
int curPos = words[i][j] - 'a';
freq[j][curPos]++;
}
}
return getWords(words,target,0,0);
}
};