Problem Solving Fundamentals · Recursion

Try a path, then back out

backtracking

Try a path, then back out

You are in a maze where each junction splits into several paths, and you want to find every route to the exit. You pick a path and walk it. If it dead-ends, you walk back to the last junction and try the next one. Remembering where you have been lets you back out cleanly instead of starting over.

That is backtracking. At each item you make a choice — take it or leave it — walk down that choice, then undo it before trying the other. Making a choice and undoing it is what lets every combination fall out of the same loop.

Name the case that stops. When you have decided about every item, there are no choices left, so you have one complete answer. That is the base case: record what you built and return.

Shrink the input by moving to the next item, one step closer to the end. Then trust the call — assume it finishes every choice after this one — and put your own choice back exactly as you found it.

function subsets(list) {
  const results = [];

  function explore(index, chosen) {
    if (index === list.length) {
      results.push(chosen.slice());

      return;
    }

    explore(index + 1, chosen);

    chosen.push(list[index]);
    explore(index + 1, chosen);
    chosen.pop();
  }

  explore(0, []);

  return results;
}

Each call decides one item and trusts the rest, and the pop undoes the choice so the next branch starts clean.

Export subsets from index.js. It returns every subset of a short list, including the empty one and the list itself.

Challenge

At every item you can take it or leave it, and each choice opens a new branch. Export a subsets function from index.js that walks every branch and collects the answers.

subsets takes a short array and returns an array of every subset, in any order. It must include the empty subset and the full array. Build each subset by choosing an item, recursing, then undoing the choice before trying the other branch.

index.js
export function subsets(_list) {
  return [];
}

export function render(mount) {
  const list = [1, 2, 3];

  mount.textContent = `subsets(${JSON.stringify(list)}) = ${JSON.stringify(subsets(list))}`;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.