|
| 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