LeetCode(40) Combination Sum II

时间:2024-01-04 21:38:26

题目

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

All numbers (including target) will be positive integers.

Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).

The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8,

A solution set is:

[1, 7]

[1, 2, 5]

[2, 6]

[1, 1, 6]

分析

与上一题39 Combination Sum本质相同,只不过需要注意两点:每个元素只能出现结果序列中一次,结果序列不可重复。

只需利用find函数添加一个判重即可。

AC代码

class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
if (candidates.empty())
return vector<vector<int> >(); sort(candidates.begin(), candidates.end()); ret.clear(); vector<int> tmp;
combination(candidates, 0, tmp, target);
return ret;
} void combination(vector<int> &candidates, int idx, vector<int> &tmp, int target)
{
if (target == 0)
{
if (find(ret.begin(), ret.end(), tmp) == ret.end())
ret.push_back(tmp);
return;
}
else{
int size = candidates.size();
for (int i = idx; i < size; ++i)
{
if (target >= candidates[i])
{
tmp.push_back(candidates[i]);
combination(candidates, i + 1, tmp, target - candidates[i]);
tmp.pop_back();
}//if
}//for
}//else
} private:
vector<vector<int> > ret;
};

GitHub测试程序源码