-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
37 lines (37 loc) · 1.13 KB
/
Solution.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
class Solution {
public:
int minStickers(vector<string>& stickers, string target) {
int n = target.size();
queue<int> q{{0}};
vector<bool> vis(1 << n);
vis[0] = true;
for (int ans = 0; q.size(); ++ans) {
for (int m = q.size(); m; --m) {
int cur = q.front();
q.pop();
if (cur == (1 << n) - 1) {
return ans;
}
for (auto& s : stickers) {
int cnt[26]{};
int nxt = cur;
for (char& c : s) {
++cnt[c - 'a'];
}
for (int i = 0; i < n; ++i) {
int j = target[i] - 'a';
if ((cur >> i & 1) == 0 && cnt[j] > 0) {
nxt |= 1 << i;
--cnt[j];
}
}
if (!vis[nxt]) {
vis[nxt] = true;
q.push(nxt);
}
}
}
}
return -1;
}
};