// Source : https://oj.leetcode.com/problems/combination-sum/ // Author : Hao Chen // Date : 2014-07-19 /********************************************************************************** * * 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] * * **********************************************************************************/ #include #include #include using namespace std; void combinationSumHelper(vector &candidates, int start, int target, vector &solution, vector< vector > &result) { if (target<0){ return; } if (target==0){ result.push_back(solution); return; } for(int i=start; istart && candidates[i] == candidates[i-1]) { continue; } solution.push_back(candidates[i]); combinationSumHelper(candidates, i, target - candidates[i], solution, result); solution.pop_back(); } } vector > combinationSum(vector &candidates, int target) { vector< vector > result; if (candidates.size()<=0){ return result; } sort(candidates.begin(), candidates.end()); vector solution; combinationSumHelper(candidates, 0, target, solution, result); return result; } void printMatrix(vector< vector > &vv) { for(int i=0; i &v) { cout << "{"; for(int i=0; i v(a, a+sizeof(a)/sizeof(int)); int target = 7; cout << "array = "; printArray(v); cout << "target = " << target << endl; vector< vector > vv = combinationSum(v, target); printMatrix(vv); return 0; }