Skip to content

Instantly share code, notes, and snippets.

@BrianJenney
Created October 29, 2022 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrianJenney/7e2c022fc33f85488cf575832a52e276 to your computer and use it in GitHub Desktop.
Save BrianJenney/7e2c022fc33f85488cf575832a52e276 to your computer and use it in GitHub Desktop.
recursive templates to make your life easier
const backtrackingProblem = (input) => {
const finalResult = []
const recurse = (curSolution, arg) => {
// base case - does our solution work?
if(isBadSolution(curSolution)) return
// add our final solution
finalResult.push([...curSolution]) // store a copy because we are gonna mutate further
for(let i=0; i<arg.length; i++){
// update our current solution with a possibility
curSolution.push(arg[i])
recurse(curSolution, arg.slice(i + 1))
// clean up our mutation
curSolution.pop()
}
}
// call the recursive helper with our initial solution and the initial input
recurse([], input)
return finalResult
}
const recurse = (arg) => {
// create a base case where we do NOT recurse
if(!arg){
return // OR return the answer for that particular argument
}else{
// create a recursive case
// call the recursive function with a new argument that gets us closer to the base case
recurse(arg - 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment