Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
stickers-to-spell-word.cpp 1.69 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2017-10-09 21:37 +08:00 . update stickers-to-spell-word.cpp
// 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];
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助