Skip to content

Instantly share code, notes, and snippets.

@sourabh2k15
Last active February 22, 2018 02:06
Show Gist options
  • Save sourabh2k15/74a9624a758808370a7fd37c33a70356 to your computer and use it in GitHub Desktop.
Save sourabh2k15/74a9624a758808370a7fd37c33a70356 to your computer and use it in GitHub Desktop.
Leetcode 39. Combination Sum solution using backtracking
class Solution {
private:
vector<int> combination;
vector<vector<int>> combinations;
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
explore(candidates, 0, target);
return combinations;
}
void explore(vector<int>& candidates, int start, int target){
if(target == 0){
combinations.push_back(combination); // yes! a valid solution found
return;
}
if(target < 0) return; // this is when we lose hope and backtrack :(
for(int i = start; i < candidates.size(); i++){
// explore all solutions using candidates[i] at least once
combination.push_back(candidates[i]);
explore(candidates, i, 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