Created
November 3, 2024 05:32
-
-
Save sAVItar02/eeae756105266a1e290ad5ead22dc276 to your computer and use it in GitHub Desktop.
Combination Sum
This file contains 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
/** | |
* @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