您的位置:首页 > 其它

Combination Sum II - LeetCode

2015-11-10 14:28 344 查看
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]


思路:和Combination Sum这道题基本思想是相同的。需要注意的不同点主要有两个:一个是因为每个数只能用一次,因此在枚举完后继续递归时要从下一位开始枚举,而不再是当前位置;另一个还是因为每个数只能用一次,因此要注意原数组中可能有重复数字的情况,因此这里在枚举过程中如果遇见了相同的数,则只枚举一次,然后跳过剩下的重复数字。

class Solution {
public:
void assist(vector<int>& candidates, vector<vector<int> >& res, vector<int>& cur, int target, int st)
{
if (target == 0)
{
res.push_back(cur);
return;
}
if (st == candidates.size()) return;
for (int i = st, n = candidates.size(); i < n && candidates[i] <= target; i++)
{
cur.push_back(candidates[i]);
assist(candidates, res, cur, target - candidates[i], i + 1);
cur.pop_back();
while (i < n && candidates[i] == candidates[i + 1])
i++;
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int> > res;
vector<int> cur;
sort(candidates.begin(), candidates.end(), less<int>());
assist(candidates, res, cur, target, 0);
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: