04
05/2015
Combination Sum II
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:
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: 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++; } } };
二次刷题(2015-08-18)
class Solution { public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { std::sort(candidates.begin(), candidates.end()); vector<vector<int>> result; helper(candidates, vector<int>(), 0, target, result); return result; } void helper(vector<int>& candidates, vector<int> item, int start, int left, vector<vector<int>>& result){ if(left == 0){ if(item.size() != 0){ result.push_back(item); } return; } if(candidates[start] > left){ return; } for(int i = start; i<candidates.size(); i++){ if(i>start && candidates[i]==candidates[i-1]){ //这里防止重复 continue; } if(left>=candidates[i]){ item.push_back(candidates[i]); helper(candidates, item, i + 1, left - candidates[i], result); //这里的i+1防止一个元素选多次 item.pop_back(); }else{ break; } } } };
转载请注明:康瑞部落 » Combination Sum II
0 条评论