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:
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]
给定一个候选数集合candidates,和一个目标值target。从候选数集合中选出所有可能的组合,使得它们的和为target。候选集中的数只能使用一次
几点说明:
1. 本题所有的数都是正数
2. 组合中的数非递减排列
3. 组合不能重复
方法和Combination Sum完全相同。
注意: 1.“候选集中的数只能使用一次”\
2. 由于候选数集合中存在重复数,因此需要注意组合的排重
class Solution { public: void dfs(vector<vector<int> >&result, vector<int>&num, int target, vector<int>combination, int sum, int startIndex){ if(sum==target)result.push_back(combination); else if(sum<target){ for(int i=startIndex; i<num.size(); i++){ if(i!=startIndex && num[i]==num[i-1])continue; //排重 if(sum+num[i]<=target){ //减少不比较递归迭代,否则会超时 combination.push_back(num[i]); dfs(result, num, target, combination, sum+num[i], i+1); combination.pop_back(); } else break; } } } vector<vector<int> > combinationSum2(vector<int> &num, int target) { vector<vector<int> > result; int size=num.size(); if(size==0)return result; sort(num.begin(), num.end()); vector<int>combination; dfs(result, num, target, combination, 0, 0); return result; } };
LeetCode: Combination Sum II [039],布布扣,bubuko.com
LeetCode: Combination Sum II [039]
原文:http://blog.csdn.net/harryhuang1990/article/details/26338787