Last active
February 22, 2018 02:06
-
-
Save sourabh2k15/74a9624a758808370a7fd37c33a70356 to your computer and use it in GitHub Desktop.
Leetcode 39. Combination Sum solution using backtracking
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
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