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
2
3
4
5
6
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
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.

Constraints:

  • n == stickers.length
  • 1 <= n <= 50
  • 1 <= stickers[i].length <= 10
  • 1 <= target <= 15
  • stickers[i] and target consist of lowercase English letters.

Solution:

  1. create mapping mp for stickers, stores character frequency of each stickers
  2. Since there might be some duplicate computation, dp to record if a subsequence is able to complete with a number of stickers.
  3. To optimize, start with a sticker that have a first character of target
  4. For each round of using a sticker, count the remainChars that needs to keep backtracking
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
35
36
37
class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
m = len(stickers)
mp = [[0]*26 for _ in range(m)] # stores freq of char in each word
for i in range(m):
for c in stickers[i]:
mp[i][ord(c)-ord('a')] += 1

dp = {}
dp[""] = 0

def backtrack(dp, mp, target):
if target in dp:
return dp[target]

n = len(mp)
tar = [0]*26
for c in target:
tar[ord(c)-ord('a')] += 1

res = float('inf')
for i in range(n): # walk through all stickers
# optimize
# start from a sticker that contains character target[0]
if mp[i][ord(target[0])-ord('a')] == 0:
continue

remainChars = ''
for j in range(26):
if tar[j] > mp[i][j]:
remainChars += chr(ord('a')+j)*(tar[j]-mp[i][j])
tmp = backtrack(dp, mp, remainChars)
if tmp != -1:
res = min(res, tmp+1)
dp[target] = -1 if res == float('inf') else res
return dp[target]
return backtrack(dp, mp, target)

time complexity: $O(26*m)$
space complexity: $O(m)$
reference:
related problem: