[LeetCode] Stickers to Spell Word

691. Stickers to Spell Word

We are given n different types of stickers. Each sticker has a lowercase English word on it.

You would like to spell out the given string target by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.

Return the minimum number of stickers that you need to spell out target. If the task is impossible, return -1.

Note: In all test cases, all words were chosen randomly from the 1000 most common US English words, and target was chosen as a concatenation of two random words.

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 {
unordered_map<string, int> dp;
int backTracking(vector<unordered_map<char,int>>& sticker, string target) {
if(dp.count(target)) return dp[target];
dp[target] = 987654321;
unordered_map<char,int> req;
for(auto ch : target)
req[ch]++;

for(auto st : sticker) {
if(!st.count(target[0])) continue;

string nTarget = "";
for(auto [ch, count] : req) {
if(count - st[ch] > 0) {
nTarget += string(count - st[ch], ch);
}
}
dp[target] = min(dp[target], 1 + backTracking(sticker, nTarget));
}
return dp[target];
}

public:
int minStickers(vector<string>& stickers, string target) {
unordered_map<char,int> t;
for(auto ch : target) t[ch]++;

vector<unordered_map<char,int>> sticker;
for(auto st : stickers) {
unordered_map<char,int> tmp;
tmp.reserve(t.size());
for(auto ch : st) {
if(t.count(ch)) {
tmp[ch]++;
}
}
if(!tmp.empty())
sticker.push_back(tmp);
}
dp[""] = 0;
int res = backTracking(sticker,target);
return res > target.length() ? -1 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/09/PS/LeetCode/stickers-to-spell-word/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.