Skip to content

Instantly share code, notes, and snippets.

@pdu
Created December 30, 2012 06:32
Show Gist options
  • Select an option

  • Save pdu/4411258 to your computer and use it in GitHub Desktop.

Select an option

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
#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