您的位置:首页 > 其它

[leetcode] 40. Combination Sum II

2016-03-03 21:52 295 查看
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题(传送门)的基础上将数字使用次数限定为一次,题目难度为Medium。

整体的处理思路是相同的,不同的是对数字使用次数的限定。由于数组元素可能重复且每个数字只能使用一次,所以在递归函数的循环中进入下层递归时要将下标加1,这样保证了每个数字只使用一次,而在39题中这里下标是不变的,这也是两题的唯一区别。另外数组中同一数字可能有多个,这样就要确保在同一层递归函数的for循环中只有第一个数字才会存入结果中,不然会出现重复的组合。在做第39题时考虑到了这点,但当时用了find函数查重,没有去想其他的方法,效率很低,现在看当时不查重处理是有问题的,这里避免重复组合的代码是学习别人的,大家也可以学习下。具体代码:
class Solution {
public:
vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
vector<vector<int>> rst;
vector<int> curRst;

sort(candidates.begin(), candidates.end());
getSum(rst, curRst, candidates, 0, 0, target);

return rst;
}

void getSum(vector<vector<int>> &rst, vector<int> &curRst, const vector<int> &candidates, int sum, int idx, int target) {
if(sum == target) {
rst.push_back(curRst);
}
else {
for(int i=idx; i<candidates.size(); ++i) {
if(sum + candidates[i] > target) return;
if(i != idx && candidates[i] == candidates[i-1]) continue;
curRst.push_back(candidates[i]);
getSum(rst, curRst, candidates, sum+candidates[i], i+1, target);
curRst.pop_back();
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode Backtracking