标签:
Title:
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]
思路:DFS搜索。与Combination Sum中的不同,每次搜索的备选项是从当前index开始到数组结束的元素。不包括重复元素。
class Solution { public: vector<vector<int> > results; vector<vector<int> > combinationSum2(vector<int> &num, int target) { if (num.empty() || num.size() == 0) return results; sort(num.begin(),num.end()); vector<int> result; combine(num,0,target,result); return results; } void combine(vector<int> &num,int startIndex, int target,vector<int> &result){ if (0 == target){ //cout<<"add"<<endl; results.push_back(result); return ; } if (0 > target) return ; for (int i = startIndex; i < num.size(); i++){ if (i > startIndex && num[i] == num[i-1]) continue; result.push_back(num[i]); combine(num,i+1,target-num[i],result); result.pop_back(); } } };
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4446715.html