Skip to content

Commit 952150f

Browse files
committed
add stickers-to-spell-word.cpp
1 parent 758b8b6 commit 952150f

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

C++/stickers-to-spell-word.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Time: O(T * S^T)
2+
// Space: O(T * S^T)
3+
4+
class Solution {
5+
public:
6+
int minStickers(vector<string>& stickers, string target) {
7+
vector<vector<int>> sticker_counts(stickers.size(), vector<int>(26));
8+
unordered_map<string, int> dp;
9+
for (int i = 0; i < stickers.size(); ++i) {
10+
for (const auto& c : stickers[i]) {
11+
++sticker_counts[i][c - 'a'];
12+
}
13+
}
14+
dp[""] = 0;
15+
return minStickersHelper(sticker_counts, target, &dp);
16+
}
17+
18+
private:
19+
int minStickersHelper(const vector<vector<int>>& sticker_counts, const string& target,
20+
unordered_map<string, int> *dp) {
21+
if (dp->count(target)) {
22+
return (*dp)[target];
23+
}
24+
int result = numeric_limits<int>::max();
25+
vector<int> target_count(26);
26+
for (const auto& c : target) {
27+
++target_count[c - 'a'];
28+
}
29+
for (const auto& sticker_count : sticker_counts) {
30+
if (sticker_count[target[0] - 'a'] == 0) {
31+
continue;
32+
}
33+
string new_target;
34+
for (int i = 0; i < target_count.size(); ++i) {
35+
if (target_count[i] - sticker_count[i] > 0) {
36+
new_target += string(target_count[i] - sticker_count[i], 'a' + i);
37+
}
38+
}
39+
if (new_target.length() != target.length()) {
40+
int num = minStickersHelper(sticker_counts, new_target, dp);
41+
if (num != -1) {
42+
result = min(result, 1 + num);
43+
}
44+
}
45+
}
46+
(*dp)[target] = (result == numeric_limits<int>::max()) ? -1 : result;
47+
return (*dp)[target];
48+
}
49+
};

0 commit comments

Comments
 (0)