Skip to content

Instantly share code, notes, and snippets.

@ysonggit
Created September 15, 2015 23:55
Show Gist options
  • Save ysonggit/5478685e16ed1eccb169 to your computer and use it in GitHub Desktop.
Save ysonggit/5478685e16ed1eccb169 to your computer and use it in GitHub Desktop.
class Solution {
public:
void dfs(vector<vector<int> >& res, vector<int>& candidates, vector<int> sol, int target, int cur_idx){
if(target==0){
res.push_back(sol);
return;
}
if(cur_idx>=candidates.size() || target < 0) return;
for(int i=cur_idx; i<candidates.size(); i++){
if(i> cur_idx && candidates[i]==candidates[i-1]) continue; // mistake : candidates[i]==candidates[cur_idx]
int cur = candidates[i];
sol.push_back(cur);
dfs(res, candidates, sol, target-cur, i+1);
sol.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int> > res;
vector<int> sol;
sort(candidates.begin(), candidates.end());
dfs(res, candidates, sol, target, 0);
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment