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 target
string 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.
What is the minimum number of stickers that you need to spell out the target
? If the task is impossible, return -1.
Example 1:
Input:
["with", "example", "science"], "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:
Input:
["notice", "possible"], "basicbasic"
Output:
-1
Explanation:
We can't form the target "basicbasic" from cutting letters from the given stickers.
Note:
stickers
has length in the range [1, 50]
.stickers
consists of lowercase English words (without apostrophes).target
has length in the range [1, 15]
, and consists of lowercase English letters.Related Topics:
Dynamic Programming, Backtracking
Similar Questions:
// OJ: https://leetcode.com/problems/stickers-to-spell-word/
// Author: github.com/lzl124631x
// Time: O(2^T * S * T)
// Space: O(2^T)
// Ref: https://leetcode.com/problems/stickers-to-spell-word/solution/
class Solution {
public:
int minStickers(vector<string>& stickers, string target) {
int N = target.size();
vector<int> dp(1 << N, -1);
dp[0] = 0;
for (int state = 0; state < 1 << N; ++state) { // a state represents the target characters matched
if (dp[state] == -1) continue; // this state is not reachable
for (auto &s : stickers) { // try each sticker
int next = state;
for (char c : s) { // for each character in the current sticker
for (int i = 0; i < N; ++i) {
if ((next >> i) & 1) continue; // if the current target character set doesn't contain the target[i], skip
if (target[i] == c) {
next |= 1 << i; // if they are matched, we can update the next state reachable
break;
}
}
}
if (dp[next] == -1 || dp[next] > dp[state] + 1) dp[next] = dp[state] + 1;
}
}
return dp[(1 << N) - 1];
}
};