|
| 1 | +/* |
| 2 | +* Given a set of candidate numbers (C) and a target number (T), find all unique |
| 3 | +* combinations in C where the candidate numbers sums to T. |
| 4 | +
|
| 5 | +* The same repeated number may be chosen from C unlimited number of times. |
| 6 | +
|
| 7 | +* Note: |
| 8 | +* All numbers (including target) will be positive integers. |
| 9 | +* Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). |
| 10 | +* The solution set must not contain duplicate combinations. |
| 11 | +* For example, given candidate set 2,3,6,7 and target 7, |
| 12 | +* A solution set is: |
| 13 | +* [7] |
| 14 | +* [2, 2, 3] |
| 15 | +
|
| 16 | + */ |
| 17 | + |
| 18 | +#include <vector> |
| 19 | +#include <algorithm> |
| 20 | +using namespace std; |
| 21 | + |
| 22 | +class Solution { |
| 23 | +public: |
| 24 | + vector<vector<int>> combinationSum(vector<int>& candidates, int target) { |
| 25 | + // sort the candidate vector in ascending order; |
| 26 | + sort( candidates.begin(), candidates.end() ); |
| 27 | + vector<vector<int> > results; |
| 28 | + vector<int> combination; |
| 29 | + sumIteration( candidates, target, results, combination, 0 ); |
| 30 | + return results; |
| 31 | + } |
| 32 | + |
| 33 | +private: |
| 34 | + void sumIteration( vector<int>& candidates, int target, vector<vector<int> >& results, vector<int>&combination, int begin ) |
| 35 | + { |
| 36 | + if( !target ) |
| 37 | + { |
| 38 | + results.push_back( combination ); |
| 39 | + return; |
| 40 | + } |
| 41 | + for( int i = begin; i< candidates.size() && target >= candidates[i]; i++ ) |
| 42 | + { |
| 43 | + combination.push_back( candidates[i] ); |
| 44 | + sumIteration( candidates, target - candidates[i], results, combination, i ); |
| 45 | + combination.pop_back(); |
| 46 | + } |
| 47 | + } |
| 48 | +}; |
| 49 | + |
| 50 | +int main( int argc, char ** argv ) |
| 51 | +{ |
| 52 | + return 0; |
| 53 | +} |
0 commit comments