Skip to content
DSA in JavaScript
← All patterns

Backtracking

0/20 solved

What it is

Build an answer one choice at a time. When a choice leads nowhere, undo it and try the next one.

Used for

Subsets, permutations, combinations, N-Queens, Sudoku, word search.
[ ][1][ ][1,2][1][2][ ]

holding [ ]

Step 1 of 7

Goal: list every subset of [1, 2]. At each number we choose: take it or skip it. All the choices form a tree of decisions. Start with nothing chosen.

You see

  • Generate all subsets, permutations or combinations
  • Place items under constraints
  • "Return all possible ..."

Learn it in

RecursionKnight's TourHamiltonian PathCartesian ProductCombinationsPower SetPermutationsCombination Sum ProblemN-Queens Problem

Template

function subsets(nums) {  const out = [], path = [];  (function go(i) {    if (i === nums.length) return out.push([...path]);    go(i + 1);                                  // skip    path.push(nums[i]); go(i + 1); path.pop();  // take, then undo  })(0);  return out;}

Practice problems