Created
October 29, 2022 14:42
-
-
Save BrianJenney/7e2c022fc33f85488cf575832a52e276 to your computer and use it in GitHub Desktop.
recursive templates to make your life easier
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
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 | |
} |
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
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