100 XP

87. All subsets

Advanced backtracking recursion

A subset of a list is any selection of its items, from none of them to all of them. [1, 2, 3] has 8 subsets: [], [1], [2], [3], [1, 2], [1, 3], [2, 3] and [1, 2, 3]. Each item is either in or out, so n items have 2^n subsets.

Write a function subsets(items) that takes a list of different whole numbers, sorted from smallest to largest, and returns all of its subsets:

  • Each subset is a list with its numbers in increasing order.
  • The empty subset [] and the whole list are both included.
  • The subsets are sorted by size, smallest first, and subsets of the same size in dictionary order: [1, 2] before [1, 3] before [2, 3].

Write the search yourself, without itertools: it is the pattern behind many backtracking problems.

Example 1

Inputitems = [1, 2, 3]
Output[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
ExplanationAll 8: by size, then in dictionary order.

Example 2

Inputitems = [5]
Output[[], [5]]
ExplanationWithout the 5, and with it.

Example 3

Inputitems = []
Output[[]]
ExplanationThe empty list has one subset: itself.

Constraints

  • items has 0 to 8 different whole numbers, from -100 to 100, sorted from smallest to largest.

Submit also runs 4 more tests you can't see.

Practises Recursion (lesson 20).

Code
def subsets(items):
    """List every subset of items.

    items: list of int, different, sorted; may be empty
    Returns: list of lists, all 2^n subsets, by size and
        then in dictionary order
    """
    # Write your code here
    pass