691.Stickers to Spell Word
Problem description:
We are given n
different types of stickers
. Each sticker has a lowercase English word on it.
You would like to spell out the given string target
by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantities of each sticker.
Return the minimum number of stickers that you need to spell out target
. If the task is impossible, return -1
.
Note: In all test cases, all words were chosen randomly from the 1000
most common US English words, and target
was chosen as a concatenation of two random words.
Example 1:
1 | Input: stickers = ["with","example","science"], target = "thehat" |
Example 2:
1 | Input: stickers = ["notice","possible"], target = "basicbasic" |
Constraints:
n == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target <= 15
stickers[i]
andtarget
consist of lowercase English letters.
Solution:
- create mapping
mp
for stickers, stores character frequency of each stickers - Since there might be some duplicate computation,
dp
to record if a subsequence is able to complete with a number of stickers. - To optimize, start with a sticker that have a first character of target
- For each round of using a sticker, count the remainChars that needs to keep backtracking
1 | class Solution: |
time complexity: $O(26*m)$
space complexity: $O(m)$
reference:
related problem: