Created
December 30, 2012 06:32
-
-
Save pdu/4411258 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.
http://www.leetcode.com/onlinejudge
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
| #include <algorithm> | |
| using namespace std; | |
| class Solution { | |
| public: | |
| void dfs(vector<vector<int> >& ret, vector<int>& tmp, vector<int>& cands, int left, int target) { | |
| if (target == 0) { | |
| ret.push_back(tmp); | |
| return; | |
| } | |
| for (int i = left; i < cands.size(); ++i) { | |
| if (target >= cands[i]) { | |
| tmp.push_back(cands[i]); | |
| dfs(ret, tmp, cands, i, target - cands[i]); | |
| tmp.pop_back(); | |
| } | |
| } | |
| } | |
| vector<vector<int> > combinationSum(vector<int> &candidates, int target) { | |
| sort(candidates.begin(), candidates.end()); | |
| vector<vector<int> > ret; | |
| vector<int> tmp; | |
| dfs(ret, tmp, candidates, 0, target); | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment