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:
For example, given candidate set
A solution set is:
*/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<vector<int>> findSum(vector<int> candidates, int size, int target){
vector<vector<int>> result;
if(size==-1) return result;
result = findSum(candidates, size-1, target);
int elem = candidates[size];
int num;
vector<int> newComb;
if(elem > target) return result;
num = target/elem;
if(target%elem == 0){
newComb.insert(newComb.begin(), num, elem);
result.push_back(newComb);
}
vector<vector<int>> inter;
int j;
int i;
for(j=1; j<=num; j++){
inter = findSum(candidates, size-1, target-j*elem);
for(i=0; i<inter.size(); i++){
inter[i].insert(inter[i].begin()+inter[i].size(), j, elem);
}
result.insert(result.begin()+result.size(), inter.begin(), inter.end());
}
return result;
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int>> result;
if(target<=0) return result;
int size = candidates.size();
int i;
set<int> inter;
for(i=0; i<size; i++){
inter.insert(candidates[i]);
}
candidates.clear();
set<int>::iterator it;
for(it=inter.begin(); it!=inter.end(); it++){
candidates.push_back(*it);
}
return findSum(candidates, size-1, target);
}
};
No comments:
Post a Comment