Skip to content

Instantly share code, notes, and snippets.

@sourabh2k15
Last active February 22, 2018 02:15
Show Gist options
  • Save sourabh2k15/ae23a99787d3f9af13db9004ebd09e29 to your computer and use it in GitHub Desktop.
Save sourabh2k15/ae23a99787d3f9af13db9004ebd09e29 to your computer and use it in GitHub Desktop.
Leetcode 40. Combinations 2 solution using backtracking
class Solution {
private:
vector<int> combination;
vector<vector<int>> combinations;
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
explore(candidates, 0, target);
return combinations;
}
void explore(vector<int>& candidates, int start, int target){
if(target == 0){
combinations.push_back(combination);
return;
}
if(target < 0) return;
for(int i = start; i < candidates.size(); i++){
if(i > start && candidates[i] == candidates[i-1]) continue; // skip duplicates
// explore all solutions using candidates[i] exactly once
combination.push_back(candidates[i]);
explore(candidates, i+1, target - candidates[i]);
// explore solutions that don't use candidates[i]
combination.pop_back();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment