LeetCode CombinationSum

时间:2023-03-08 22:27:26
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) { sort(candidates.begin(), candidates.end());
candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end()); vector<vector<int> > tmp;
vector<int> sel; dfs(candidates, , target, sel, tmp);
return tmp;
} void dfs(vector<int>& nums, int pos, int tar, vector<int>& sel, vector<vector<int> >& res) {
if (tar == ) {
res.push_back(sel);
return;
}
if (pos >= nums.size()) return;
int cur = nums[pos];
int add = ;
for (add = ; add <= tar; add+=cur) {
if (add != ) {
sel.push_back(cur);
}
dfs(nums, pos + , tar - add, sel, res);
}
for (int i = add/cur - ; i>; i--) {
sel.pop_back();
}
}
};

dfs搜索,通过unique操作去除重复的候选数字,避免产生重复的序列