The pick-or-skip tree: generating subsequences

Video lessonComing soon

1 Take it or leave it

We are packing for a trip. Three things lie on the bed: a camera, a pair of shoes and a blanket. They weigh 1, 2 and 3 kg, and from now on we call each one by its weight. We want every way to pack the bag, from empty to all three.

Three nested loops would do for three things, but n changes from one input to the next. The bitmasks lesson counted masks from 0 to 2ⁿ − 1 instead. This lesson packs the way a person does. We pick up the first thing and decide: take it or leave it. Then the second, then the third. Two answers for each of three things give 2 × 2 × 2 = 8 ways.

In code, the things are nums = [1, 2, 3], and one way to pack is a subsequence: some of the values, in their original order. Three words get mixed up here:

WordWhat it keepsHow many in [1, 2, 3]
SubarrayValues next to each other6, about n² in general
SubsequenceAny values, in their original order8 with the empty one, 2ⁿ in general
SubsetAny values, in any order8, the same choices

[1, 3] is a subsequence but not a subarray, because 2 sits between them. Subsets come from the same choices, so this lesson lists them too.

2 The pick-or-skip tree

We draw the decisions as a tree. Level 1 decides 1, level 2 decides 2 and level 3 decides 3. Each node shows the decisions so far: a number for a value we took, and a dot for one we left. The left branch takes, and the right branch leaves. The first decision splits the tree into two halves:

1231212·11·31·1··
Took 1
·23·2·2····3·····
Left 1

This is the pick-or-skip tree. Its 8 leaves are the 8 ways to pack. Each leaf ends exactly one path of decisions, so every way shows up once, and none is missed. Each level doubles the nodes, so n values give 2ⁿ leaves.

In code, each node is one call, pickOrSkip(i), and it decides nums[i]. It makes two calls on i + 1: one after taking nums[i] and one after leaving it. When i reaches n, every value is decided. That call is a leaf, the base case.

3 Walking the tree with one list

The calls do not run level by level. The program goes down the leftmost path first, then comes back up and tries the next branch. So it reaches the leaves from left to right.

We keep one list, current, for the bag as it stands, and every call shares it. Picking adds the value to its end. At a leaf, current holds a finished bag, so we save a copy of it in result.

Here is the walk through the half that takes 1:

Walking the half that takes 1
1231212·11·31·1··
Pick 1: add it to current
1012
current
                            
result

Step 4 is the key move. When the call that took 3 returns, 3 is still in current. Before the skip branch runs, we remove it, so the bag is back to how it was before the pick. This is the undo. Every pick is followed by removing the same value, right after its call returns.

The half that leaves 1 starts from the empty current of step 8 and saves the other four bags. Here are all 8 leaves in the order the walk reaches them, with the weight of each bag:

OrderLeafSavedWeight
1123[1, 2, 3]6
212·[1, 2]3
31·3[1, 3]4
41··[1]1
5·23[2, 3]5
6·2·[2]2
7··3[3]3
8···[]0

4 The code

The code follows the walk line for line: pick, call, undo, then skip. It solves Subsets, which asks for every subset of nums.

On [1, 2, 3], every tab returns [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]: the leaves from left to right.

C++

push_back copies. result.push_back(current) stores a copy of the vector, so later changes to current do not touch it. The & on current matters the other way: without it, every call gets its own copy of the whole vector.

Save a copy. result.add(current) would store a reference to the one shared list. The undos empty it by the end, so the answer would be eight empty lists. new ArrayList<>(current) stores a copy.

Save a copy. result.append(current) would store the one shared list eight times. The undos empty it by the end, so the answer would be eight empty lists. current.copy() stores a copy.

Save a copy. result.push(current) would store the one shared array eight times. The undos empty it by the end, so the answer would be eight empty arrays. [...current] stores a copy.

Save a copy. Appending current itself stores a slice that shares memory with current, and later picks write over its values. make and copy give each saved bag its own memory.

The compiler asks for the copy. result cannot keep current, which is only borrowed, so we push current.clone().

Save a copy. result.Add(current) would store a reference to the one shared list. The undos empty it by the end, so the answer would be eight empty lists. new List<int>(current) stores a copy.

The order of the output. Pick runs before skip, so the fuller bags come first. If we swap the two parts, skip runs first, and the same 8 lists come out in reverse: [], [3], [2], [2,3], and so on up to [1,2,3]. Subsets accepts any order. When a problem asks for one order, the order of the two branches sets it.

5 Counting and finding: return the answer up

Often a problem wants a number about the bags, not the bags. How many ways to pack weigh exactly 3 kg? The table shows two: [1, 2] and [3].

A leaf needs only the weight of its bag. So we drop current and pass the weight down, as in the lesson on passing the answer down. Each call returns how many leaves below it weigh k, the target. It adds up the answers of its two branches:

countWays(i, weight)
    if i == n
        if weight == k
            return 1
        return 0
    picked = countWays(i + 1, weight + nums[i])
    skipped = countWays(i + 1, weight)
    return picked + skipped

Here is what each call returns for k = 3, on the same two halves:

0111000
Took 1: returns 1
0001110
Left 1: returns 1

Only the leaves 12· and ··3 return 1, and the bold paths lead to them. Each half returns 1, so the first call returns 1 + 1 = 2. The weight goes down the tree, and the count comes back up.

Finding one. Can we pack exactly 5 kg? One yes is enough, so the call returns true as soon as a branch does:

canPack(i, weight)
    if i == n
        return weight == k
    if canPack(i + 1, weight + nums[i])
        return true
    return canPack(i + 1, weight)

With k = 5, the walk stops at ·23, the fifth leaf, and true goes straight up. When no bag works, such as with k = 7, it still visits all 8 leaves.

6 Cost and how large n can be

The tree has 2ⁿ leaves and about as many calls above them, so about 2 × 2ⁿ calls in all. The work in each call sets the time:

  • Listing. Each leaf copies up to n values, so the time is O(n × 2ⁿ). The answer itself holds about n × 2ⁿ / 2 values, since each value is in half the bags, so no method lists faster.
  • Counting or finding. Each call does O(1) work, so the time is O(2ⁿ).
  • Space. The call stack holds one path at a time, n + 1 frames, and current holds at most n values. That is O(n), besides the answer.

A copy instead of the undo. Each pick call could get its own new list, with nums[i] added. Nothing is shared, so no undo is needed. But every pick then copies up to n values, about n × 2ⁿ steps, even when the problem saves only a few leaves. With the shared list, only a saved leaf pays for a copy.

The cost doubles with every value:

nLeaves, 2ⁿListing, n × 2ⁿ
10about 10³about 10⁴
20about 10⁶about 2 × 10⁷
30about 10⁹about 3 × 10¹⁰

At n = 20, both fit easily. At n = 30, even counting makes about 2 × 10⁹ calls. At about 10⁸ steps a second, that is far past the time limit, so it gets TLE. So the tree fits when n is about 20 or less.

7 Mistakes and edge cases

  • Forgetting the undo. The skip branch then still sees the picked value. On [1, 2, 3], the second leaf saves [1, 2, 3] again instead of [1, 2], and later bags keep growing.
  • Saving current itself. In most languages, result then holds the one shared list eight times, and the undos empty it by the end. The note under the code shows the copy.
  • The base case one level early. With if i == n - 1, the calls stop before deciding the last value. On [1, 2, 3], the answer is [1, 2], [1], [2] and [], and 3 is never packed.
  • The empty bag. The leaf ··· weighs 0, so for k = 0 it counts. When a problem wants at least one value, that leaf must not count.
  • Overflow. Twenty values of 10⁹ add up to 2 × 10¹⁰, past the 32-bit limit of about 2 × 10⁹. Keep the weight in long long.
  • Equal values. On [1, 2, 2], [1, 2] comes out twice, once with each 2. To list each bag once, we sort nums, and the skip branch skips every copy of the value, not just one. Subsets II needs this.

8 When to use it

The sign is a problem where each value is either in or out, and we need every choice or a count of them, with n at most about 20. The tree bends to fit the question:

  • List every choice. Share one current, undo each pick, and save a copy at each leaf.
  • Count the choices. Pass the running sum down, and return the count up.
  • Find one choice. Return true up, and stop at the first leaf that works.
  • A rule between neighbours. In a binary string of length n, each position takes a 0 or a 1, the same two-way choice. A rule such as "no two 1s next to each other" means one branch is sometimes not allowed, so that call is never made.

The pruning lesson goes further and cuts a branch as soon as it cannot lead to an answer. When a call has more than two choices, such as which value goes next in a permutation, the backtracking lesson loops over them, with the same choose, explore and undo.

The habit to keep: before writing the recursion, draw the first two levels of the tree and write what each node holds. Then put the undo right after the call that needs it.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.