[LeetCode] Combination Sum
2015-05-04 10:52:52         来源：康瑞部落

Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

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 `2,3,6,7` and target `7`,
A solution set is:
`[7]`
`[2, 2, 3]`

```class Solution {
public:
vector> combinationSum(vector& candidates, int target) {
vector> result;
int len=candidates.size();
if(len==0){
return result;
}
std:sort(candidates.begin(), candidates.end());
map keyToNumber;  //相当于系数,表示每个数出现了多少次
getResult(result, candidates, 0, keyToNumber, target);
}

void getResult(vector>& result, vector& uniqueCandidates, int candidateIndex, map& keyToNumber, int left){
if(left<0){
return;
}
if(left==0){
vector item;
for(map::iterator it=keyToNumber.begin(); it!=keyToNumber.end(); it++){
int number=it->second;
int key = it->first;
for(int i=0; i=uniqueCandidates.size()){
return;
}
int number=0;
while(left>=0){
if(number!=0)
keyToNumber[uniqueCandidates[candidateIndex]]=number;
getResult(result, uniqueCandidates, candidateIndex+1, keyToNumber, left);
if(number!=0){
keyToNumber.erase(uniqueCandidates[candidateIndex]);
}
left = left-uniqueCandidates[candidateIndex];
number++;
}
}
};```