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.
解题思路:
这是一道拼接题,也就是说只要凑够target中所有相应个数的字母,就可以拼出target,所以不用遍历target的字母依次找属于字符串。
class Solution {
public:
int minStickers(vector<string>& stickers, string target)
{
int len = stickers.size() ;
vector<vector<int> > match(len , vector<int>(26 , 0)) ;
for(int i = 0 ; i < len ; ++i)
{
for(auto c : stickers[i]) match[i][c - 'a']++ ;
}
unordered_map<string , int> dp ;
dp[""] = 0 ;
return DFS(stickers , dp , match , target) ;
}
private :
int DFS(vector<string> & stickers , unordered_map<string , int> & dp ,vector<vector<int>> & match , string target)
{
if(dp.count(target)) return dp[target] ;
vector<int> tar(26 , 0) ;
int res = INT_MAX ;
for(auto c : target) tar[c - 'a']++ ;
for(int i = 0 ; i < stickers.size() ; ++i)
{
if(match[i][target[0] - 'a'] == 0) continue ;
string s ;
for(int j = 0 ; j < 26 ; ++j)
{
if(tar[j] > match[i][j]) s += string(tar[j] - match[i][j] , 'a'+j) ;
}
int tmp = DFS(stickers , dp , match , s) ;
if(tmp != -1)
{
res = min(res , 1 + tmp) ;
}
}
dp[target] = res == INT_MAX ? -1 : res ;
return dp[target] ;
}
};