Combination Sum II
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]
解题思路:
与combination sum类似,与之不同的是,每个候选元素只能用一次。
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { vector<vector<int>> result; int len=candidates.size(); if(len==0){ return result; } std:sort(candidates.begin(), candidates.end()); map<int, int> keyToNumber; //相当于系数,表示每个数出现了多少次,注意,这里变成下标,而非数了。 set<vector<int>> contains; //是否包含了这组解 getResult(result, contains, candidates, 0, keyToNumber, target); } void getResult(vector<vector<int>>& result, set<vector<int>>& contains, vector<int>& uniqueCandidates, int candidateIndex, map<int, int>& keyToNumber, int left){ if(left<0){ return; } if(left==0){ vector<int> item; for(map<int, int>::iterator it=keyToNumber.begin(); it!=keyToNumber.end(); it++){ int number=it->second; int key = it->first; for(int i=0; i<number; i++){ item.push_back(uniqueCandidates[key]); } } if(contains.find(item)==contains.end()){ result.push_back(item); contains.insert(item); } return; } if(candidateIndex>=uniqueCandidates.size()){ return; } int number=0; while(left>=0&&number<2){ //用0次或一次 if(number!=0) keyToNumber[candidateIndex]=number; getResult(result, contains, uniqueCandidates, candidateIndex+1, keyToNumber, left); if(number!=0){ keyToNumber.erase(candidateIndex); } left = left-uniqueCandidates[candidateIndex]; number++; } } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45480979