Created
February 19, 2013 06:22
-
-
Save zhoutuo/4983552 to your computer and use it in GitHub Desktop.
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 orde…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int> > combinationSum(vector<int> &candidates, int target) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
sort(candidates.begin(), candidates.end()); | |
vector<int> curResult; | |
vector<vector<int> > results; | |
solve(candidates, target, results, 0, curResult); | |
return results; | |
} | |
void solve(vector<int>& candidates, int target, vector<vector<int> >& results, int cur, vector<int>& curResult) { | |
if(target < 0) { | |
return; | |
} else if(target == 0) { | |
results.push_back(curResult); | |
return; | |
} | |
for(int i = cur; i < candidates.size(); ++i) { | |
curResult.push_back(candidates[i]); | |
solve(candidates, target - candidates[i], results, i, curResult); | |
curResult.pop_back(); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment