forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stickers-to-spell-word.cpp
49 lines (47 loc) · 1.69 KB
/
stickers-to-spell-word.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
// Time: O(T * S^T)
// Space: O(T * S^T)
class Solution {
public:
int minStickers(vector<string>& stickers, string target) {
vector<vector<int>> sticker_counts(stickers.size(), vector<int>(26));
unordered_map<string, int> dp;
for (int i = 0; i < stickers.size(); ++i) {
for (const auto& c : stickers[i]) {
++sticker_counts[i][c - 'a'];
}
}
dp[""] = 0;
return minStickersHelper(sticker_counts, target, &dp);
}
private:
int minStickersHelper(const vector<vector<int>>& sticker_counts, const string& target,
unordered_map<string, int> *dp) {
if (dp->count(target)) {
return (*dp)[target];
}
int result = numeric_limits<int>::max();
vector<int> target_count(26);
for (const auto& c : target) {
++target_count[c - 'a'];
}
for (const auto& sticker_count : sticker_counts) {
if (sticker_count[target[0] - 'a'] == 0) {
continue;
}
string new_target;
for (int i = 0; i < target_count.size(); ++i) {
if (target_count[i] - sticker_count[i] > 0) {
new_target += string(target_count[i] - sticker_count[i], 'a' + i);
}
}
if (new_target.length() != target.length()) {
int num = minStickersHelper(sticker_counts, new_target, dp);
if (num != -1) {
result = min(result, 1 + num);
}
}
}
(*dp)[target] = (result == numeric_limits<int>::max()) ? -1 : result;
return (*dp)[target];
}
};