Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/691.html
691. Stickers to Spell Word
Level
Hard
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 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.- In all test cases, all words were chosen randomly from the 1000 most common US English words, and the target was chosen as a concatenation of two random words.
- The time limit may be more challenging than usual. It is expected that a 50 sticker test case can be solved within 35ms on average.
Solution
This problem can be converted into a complete knapsack problem, where each sticker can be used infinite times.
Create an array dp
of length 1 << target.length()
, where dp[i]
represents the minimum number of stickers for state i
, and -1 means impossible. Initialize all elements in dp
to -1 and initialize dp[0] = 0
. Then for each sticker, compare each letter with each letter in target
. If there is a match, then update the new state’s value in dp
. Finally, return dp[(1 << target.length()) - 1]
.
-
class Solution { public int minStickers(String[] stickers, String target) { int stickersCount = stickers.length, targetLength = target.length(); int[] dp = new int[1 << targetLength]; Arrays.fill(dp, -1); dp[0] = 0; for (String sticker : stickers) { for (int state = 0; state < 1 << targetLength; state++) { if (dp[state] >= 0) { int curState = state; int stickerLength = sticker.length(); for (int i = 0; i < stickerLength; i++) { char c = sticker.charAt(i); for (int j = 0; j < targetLength; j++) { if (c == target.charAt(j) && (curState & (1 << j)) == 0) { curState |= 1 << j; break; } } } if (dp[curState] == -1) dp[curState] = dp[state] + 1; else dp[curState] = Math.min(dp[curState], dp[state] + 1); } } } return dp[(1 << targetLength) - 1]; } }
-
// OJ: https://leetcode.com/problems/stickers-to-spell-word/ // 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]; } };
-
class Solution: def minStickers(self, stickers: List[str], target: str) -> int: q = deque([0]) ans = 0 n = len(target) vis = [False] * (1 << n) vis[0] = True while q: for _ in range(len(q)): state = q.popleft() if state == (1 << n) - 1: return ans for s in stickers: nxt = state cnt = Counter(s) for i, c in enumerate(target): if not (nxt & (1 << i)) and cnt[c]: nxt |= 1 << i cnt[c] -= 1 if not vis[nxt]: vis[nxt] = True q.append(nxt) ans += 1 return -1
-
func minStickers(stickers []string, target string) int { q := []int{0} n := len(target) vis := make([]bool, 1<<n) vis[0] = true ans := 0 for len(q) > 0 { for t := len(q); t > 0; t-- { state := q[0] if state == (1<<n)-1 { return ans } q = q[1:] for _, s := range stickers { nxt := state cnt := make([]int, 26) for _, c := range s { cnt[c-'a']++ } for i, c := range target { idx := c - 'a' if (nxt&(1<<i)) == 0 && cnt[idx] > 0 { nxt |= 1 << i cnt[idx]-- } } if !vis[nxt] { vis[nxt] = true q = append(q, nxt) } } } ans++ } return -1 }
-
use std::collections::{HashSet, VecDeque}; impl Solution { pub fn min_stickers(stickers: Vec<String>, target: String) -> i32 { let mut q = VecDeque::new(); q.push_back(0); let mut ans = 0; let n = target.len(); let mut vis = HashSet::new(); vis.insert(0); while !q.is_empty() { for _ in 0..q.len() { let state = q.pop_front().unwrap(); if state == (1 << n) - 1 { return ans; } for s in &stickers { let mut nxt = state; let mut cnt = [0; 26]; for &c in s.as_bytes() { cnt[(c - b'a') as usize] += 1; } for (i, &c) in target.as_bytes().iter().enumerate() { let idx = (c - b'a') as usize; if (nxt & (1 << i)) == 0 && cnt[idx] > 0 { nxt |= 1 << i; cnt[idx] -= 1; } } if !vis.contains(&nxt) { q.push_back(nxt); vis.insert(nxt); } } } ans += 1; } -1 } }