Miscellaneous problems · Exercise 80 of 100

Generate subsets

To list the subsets of a set, visit each distinct item once in a fixed order. For each item, follow one branch that includes it and another that skips it. Every finished branch gives a different subset because it records one choice for every item.

Try it yourself

An ice cream stand offers mint, nuts and figs as toppings. Among all topping subsets, how many include mint?

One-step hint

Put mint in every subset from the start. Draw a take-or-skip branch for nuts and another for figs, then count the branch endings.

Worked solution
  1. Keep the branch that includes mint. If you skip nuts, the two possibilities are mint alone and mint with figs.
  2. If you include nuts, you can again skip or include figs. Those two more subsets bring the count to 4.
DSA compiler

Explore the idea visually in the backtracking with subsets lab.