← All coursesDSA Foundations

Lesson 18 of 19

Backtracking with subsets

Pack a bag by deciding once per item whether to take it or skip it. After the last decision, save a copy of the bag. Undo a choice before exploring its sibling.

Save the bag before undoing a choice

A branch fixes one decision per item. At the end of a branch, copy the current bag so that future changes leave that result intact. Returning from the branch lets you restore the bag and try the other choice.

Work through an example

You have a red tile R and a blue tile B. Decide about R first. At each tile, try taking it before skipping it. Which bags do you save, in order?

Step-by-step solution
  1. Take R. Taking B gives [R, B]. Remove B and skip it to save [R].
  2. Remove R and explore the branch that skips it. Taking B now gives [B].
  3. Remove B and skip it. Save the empty bag as the fourth result. Every pair of take-or-skip decisions produced one bag.
JavaScript example
const tiles = ["R", "B"];
const bag = [];
const bags = [];

function pack(index) {
  if (index === tiles.length) {
    bags.push([...bag]);
    return;
  }
  bag.push(tiles[index]);
  pack(index + 1);
  bag.pop();
  pack(index + 1);
}

pack(0);
bags;
DSA compiler

Try it yourself

Finish the animation to unlock this question.

You just saved the bag [R, B]. You want to explore the other choice for B while keeping R. What do you undo?

Related exercise · Generate subsets · See this stage of the beginner path