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 outtarget. 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.
Input:
stickers = ["with","example","science"], target = "thehat"
Output:
3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
1
2
3
4
5
6
Input:
stickers = ["notice","possible"], target = "basicbasic"
Output:
-1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
The main idea is to use dynamic programming with memoization to avoid recalculating the minimum stickers needed for the same sub-target. By representing the remaining target as a string, we can recursively try all sticker combinations and cache results for efficiency.
classSolution {
funminStickers(stickers: Array<String>, target: String): Int {
val n = stickers.size
val freq = Array(n) { IntArray(26) }
for (i in0 until n)
for (c in stickers[i]) freq[i][c - 'a']++val memo = mutableMapOf("