- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Backtracking Explained
Backtracking
Backtracking Explained
Backtracking is brute force with an eraser. You try a choice, follow it, and if it leads nowhere you undo it and try the next - which is why the undo step is the part that matters.
The template
Every backtracking solution is this shape:
Choose, explore, unchoose
javascript
// A runnable instance of the template: every 2-element combination.
function backtrack(current, options, results, start) {
if (current.length === 2) { // a complete solution
results.push([...current]) // copy — current keeps changing
return
}
for (let i = start; i < options.length; i++) {
current.push(options[i]) // choose
backtrack(current, options, results, i + 1) // explore
current.pop() // unchoose
}
}
const results = []
backtrack([], ["a", "b", "c"], results, 0)
console.log(results) // [["a","b"], ["a","c"], ["b","c"]]