forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
41 lines (41 loc) · 1.18 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
38
39
40
41
class Solution {
public:
int minStickers(vector<string>& stickers, string target) {
queue<int> q{{0}};
int ans = 0;
int n = target.size();
vector<bool> vis(1 << n);
vis[0] = true;
while (!q.empty())
{
for (int t = q.size(); t; --t)
{
int state = q.front();
if (state == (1 << n) - 1) return ans;
q.pop();
for (auto& s : stickers)
{
int nxt = state;
vector<int> cnt(26);
for (char& c : s) ++cnt[c - 'a'];
for (int i = 0; i < n; ++i)
{
int idx = target[i] - 'a';
if (!(nxt & (1 << i)) && cnt[idx])
{
nxt |= 1 << i;
--cnt[idx];
}
}
if (!vis[nxt])
{
vis[nxt] = true;
q.push(nxt);
}
}
}
++ans;
}
return -1;
}
};