【发布时间】:2021-09-12 09:36:52
【问题描述】:
我正在尝试解决Combination II,这类似于硬币兑换问题,具有独特的组合,硬币没有无限重复。
例如:coins: {1,2,4}, amount = 3
{1,1,1,1} 或 {1,1,2} 不允许,因为硬币 1 的频率是一次。(单个硬币只能使用一次)
{1,1,4} ,amount=3
{1,1,2} --> 将被允许,因为这两个来自两个不同的 1 硬币。
工作代码: https://ide.geeksforgeeks.org/5fjEmsWXUr
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector <vector <vector <int>>> dp(target+1);
dp[0] = {{}};
//traverse throuugh coins
for (int i=0; i<candidates.size()-1; i++){
// traverse through DP (amount -> 0 inclusive)
for(int j = target; j>=candidates[i]; j--){ // just reverse it start with target and use target-coin amount to fill. In this way we are just adding current number not repeating the same no. infinite times as done in j = candidates[i] to target+1;
// order repetition will be there.
for(auto v: dp[j-candidates[i]]){
v.push_back(candidates[i]);
dp[j].push_back(v);
}
}
}
return dp[target];
}
};
您的意见
[10,1,2,7,6,1,5]
8
输出
[[1,2,5],[1,2,5],[1,1,6],[2,6],[1,7],[1,7]]
预期
[[1,1,6],[1,2,5],[1,7],[2,6]]
就我而言:
[1,2,5] 出现了两次,[1,7] 也出现了。
我想删除这些重复项。
我知道我们可以使用set 来存储它们。但是我在使用set 和修改函数返回类型时遇到了问题。
【问题讨论】:
-
如果您使用
std::set而不是std::vector它不能包含重复项。你遇到了什么问题? -
@463035818_is_not_a_number:我知道我必须使用 set。只是我不习惯使用 set。还必须在代码中进行修改,我得到了错误:'(。
-
set 可能是最有效的,另一种方法是如果它已经存在则不添加任何内容。例如使用 std::find_if。 (虽然这个例子可能会变得太慢)
-
函数必须返回一个
vector<vector<int>>?然后使用set<vector<int>>,只有当你返回它时,你才会创建向量 -
“必须在代码中进行修改”确保你这样做。不更改代码就无法更改代码。 “我也遇到了错误”请显示损坏的代码和错误