代码拉取完成,页面将自动刷新
// Time: O(T * S^T)
// Space: O(T * S^T)
class Solution {
public:
int minStickers(vector<string>& stickers, string target) {
vector<vector<int>> sticker_counts(stickers.size(), vector<int>(26));
unordered_map<string, int> dp;
for (int i = 0; i < stickers.size(); ++i) {
for (const auto& c : stickers[i]) {
++sticker_counts[i][c - 'a'];
}
}
dp[""] = 0;
return minStickersHelper(sticker_counts, target, &dp);
}
private:
int minStickersHelper(const vector<vector<int>>& sticker_counts, const string& target,
unordered_map<string, int> *dp) {
if (dp->count(target)) {
return (*dp)[target];
}
int result = numeric_limits<int>::max();
vector<int> target_count(26);
for (const auto& c : target) {
++target_count[c - 'a'];
}
for (const auto& sticker_count : sticker_counts) {
if (sticker_count[target[0] - 'a'] == 0) {
continue;
}
string new_target;
for (int i = 0; i < target_count.size(); ++i) {
if (target_count[i] - sticker_count[i] > 0) {
new_target += string(target_count[i] - sticker_count[i], 'a' + i);
}
}
if (new_target.length() != target.length()) {
int num = minStickersHelper(sticker_counts, new_target, dp);
if (num != -1) {
result = min(result, 1 + num);
}
}
}
(*dp)[target] = (result == numeric_limits<int>::max()) ? -1 : result;
return (*dp)[target];
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。