Skip to content

Commit 71848dc

Browse files
committed
Add solution #691
1 parent 3b1bf1b commit 71848dc

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,7 @@
522522
688|[Knight Probability in Chessboard](./0688-knight-probability-in-chessboard.js)|Medium|
523523
689|[Maximum Sum of 3 Non-Overlapping Subarrays](./0689-maximum-sum-of-3-non-overlapping-subarrays.js)|Hard|
524524
690|[Employee Importance](./0690-employee-importance.js)|Medium|
525+
691|[Stickers to Spell Word](./0691-stickers-to-spell-word.js)|Hard|
525526
692|[Top K Frequent Words](./0692-top-k-frequent-words.js)|Medium|
526527
693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy|
527528
695|[Max Area of Island](./0695-max-area-of-island.js)|Medium|
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 691. Stickers to Spell Word
3+
* https://leetcode.com/problems/stickers-to-spell-word/
4+
* Difficulty: Hard
5+
*
6+
* We are given n different types of stickers. Each sticker has a lowercase English word on it.
7+
*
8+
* You would like to spell out the given string target by cutting individual letters from your
9+
* collection of stickers and rearranging them. You can use each sticker more than once if you
10+
* want, and you have infinite quantities of each sticker.
11+
*
12+
* Return the minimum number of stickers that you need to spell out target. If the task is
13+
* impossible, return -1.
14+
*
15+
* Note: In all test cases, all words were chosen randomly from the 1000 most common US English
16+
* words, and target was chosen as a concatenation of two random words.
17+
*/
18+
19+
/**
20+
* @param {string[]} stickers
21+
* @param {string} target
22+
* @return {number}
23+
*/
24+
var minStickers = function(stickers, target) {
25+
const dp = new Map([['', 0]]);
26+
return helper(target);
27+
28+
function helper(str) {
29+
if (dp.has(str)) return dp.get(str);
30+
let result = Infinity;
31+
32+
for (const s of stickers.filter(s => s.includes(str[0]))) {
33+
result = Math.min(result, 1 + helper(calcDiff(str, s)));
34+
}
35+
36+
dp.set(str, result === Infinity || result === 0 ? -1 : result);
37+
return dp.get(str);
38+
}
39+
40+
function calcDiff(str1, str2) {
41+
for (const c of str2) {
42+
if (str1.includes(c)) str1 = str1.replace(c, '');
43+
}
44+
return str1;
45+
}
46+
};

0 commit comments

Comments
 (0)