Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 3, 2024 05:32
Show Gist options
  • Save sAVItar02/eeae756105266a1e290ad5ead22dc276 to your computer and use it in GitHub Desktop.
Save sAVItar02/eeae756105266a1e290ad5ead22dc276 to your computer and use it in GitHub Desktop.
Combination Sum
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
let answer = [];
let stack = [];
let findCombinations = (index, targetToFind, stack, answer, candidates) => {
if(index === candidates.length) {
if(targetToFind === 0) {
answer.push([...stack]);
}
return;
}
if(targetToFind === 0) {
answer.push([...stack]);
return;
}
if(candidates[index] <= targetToFind) {
stack.push(candidates[index])
findCombinations(index, targetToFind - candidates[index], stack, answer, candidates);
stack.pop();
}
findCombinations(index + 1, targetToFind, stack, answer, candidates);
}
findCombinations(0, target, stack, answer, candidates);
return answer;
};
// Backtraking
// explanation: https://www.youtube.com/watch?v=OyZFFqQtu98
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment