-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.ts
34 lines (34 loc) · 1.07 KB
/
Solution.ts
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
function minStickers(stickers: string[], target: string): number {
const n = target.length;
const q: number[] = [0];
const vis: boolean[] = Array(1 << n).fill(false);
vis[0] = true;
for (let ans = 0; q.length; ++ans) {
const qq: number[] = [];
for (const cur of q) {
if (cur === (1 << n) - 1) {
return ans;
}
for (const s of stickers) {
const cnt: number[] = Array(26).fill(0);
for (const c of s) {
cnt[c.charCodeAt(0) - 97]++;
}
let nxt = cur;
for (let i = 0; i < n; ++i) {
const j = target.charCodeAt(i) - 97;
if (((cur >> i) & 1) === 0 && cnt[j]) {
nxt |= 1 << i;
cnt[j]--;
}
}
if (!vis[nxt]) {
vis[nxt] = true;
qq.push(nxt);
}
}
}
q.splice(0, q.length, ...qq);
}
return -1;
}