Six problems that count the subsets, combinations or orders that obey a rule. The move: choose, explore, undo, and test every choice against the rules before making it, so dead branches are never entered.
You work on a sticker app, a coupon wallet and a pickup planner. Each asks how many subsets or orders obey some rules, and each count is too large to list one by one.
The Academy lessons Subsets and permutations and Backtracking with pruning show the walk: choose, explore, undo. This street keeps the walk and changes the rules. The table shows the rule for each problem.
| Problem | A choice is | The rule tested before it | Equal items |
|---|---|---|---|
| Sticker packs | take a pack or not | no clash, total within the cap | all different |
| Coupon bundles | take a coupon or not | the total fits the modulus at the end | skip a repeat at the same level |
| Placement plans | one more tier | picks and budget cannot overshoot | prices are different |
| Stage orders | the next stage | the hand-off is allowed | all different |
| Pickup orders | the next zone | not the same as the last zone | choose a kind, count per kind |
| Playlist skips | none: a position | none | all different |
Read the third column first. A rule that is tested before the choice cuts a whole branch off the tree.
Exercise · Predict the output: Packs that clash. Four packs have sizes 3, 2, 4 and 1. Packs 0 and 1 clash, so they cannot both be kept, and kept sizes must total at most 6. The code counts every valid set, including the empty one. What does it print?
sizes = [3, 2, 4, 1]
cap = 6
blocked = [0, 0, 0, 0]
for a, b in [[0, 1]]:
blocked[a] |= 1 << b
blocked[b] |= 1 << a
def go(i, mask, total):
if i == 4:
return 1
count = go(i + 1, mask, total)
if total + sizes[i] <= cap and not (mask & blocked[i]):
count += go(i + 1, mask | 1 << i, total + sizes[i])
return count
print(go(0, 0, 0))A search tree has one level for each decision. At each level the walk tries the choices that are open, and each choice leads to a smaller problem.
The partial answer always satisfies every rule so far. A choice is tested before it is made, and made only if the answer stays valid. After exploring it, the walk undoes the choice and tries the next one.
The test is the whole saving. A branch that fails the test is cut at its root, and everything below it is never visited. For the 4 packs above, the walk makes 20 calls, where the same walk with no test makes 31.
Equal items need a second decision. If the coupons are 1, 1 and 2, there are 8 subsets by position but only 6 different bundles. Sort the values, and at each level skip a value that equals the one tried before it at that level. The bundles come out distinct without a set.
When the items are riders in zones, choose a zone and not a rider, and keep a count for each zone. Then two riders of the same zone can never produce the same order twice.
Test a choice before you make it. A failed test cuts a whole branch, and the count stays exact.
Exercise · Find the bug: Skip at the same level. Coupons may repeat in value. A bundle is a set of coupons, and two bundles are the same when they hold the same values the same number of times. The function counts the different bundles. Which line is wrong?
def count_distinct_bundles(values):
values = sorted(values)
count = 0
def pick(start):
nonlocal count
count += 1
for i in range(start, len(values)):
if i > 0 and values[i] == values[i - 1]:
continue
pick(i + 1)
pick(0)
return countSubsets and permutations lists every subset and order, and Backtracking with pruning cuts branches. This street changes four things.
You count, you do not list. With the sticker packs, the answer is 9, one number. The walk returns a count from each branch and adds them up, so nothing is stored. Counting makes the largest inputs possible, because the number of answers may be huge.
A rule can need the whole answer so far. For placements with prices 1, 2, 3 and 5, exactly 3 picks and a budget of 8, a tier can repeat. The plans are 1, 2, 5 and 2, 3, 3, which is 2 of the 20 ways to pick. A branch stops when the picks left cannot reach the budget left.
Equal riders give a kind. With riders in zones 0, 0, 1, 1 and 2, there are 30 distinct orders and 12 of them never place a zone twice in a row. With zones 0, 0, 0 and 1, there are 4 orders and none is valid. Choose a zone and keep a count for each zone.
The answer can be a position. For a playlist of 1, 2, 3, 4 after 5 skips, the order is 1, 4, 3, 2. After 30 skips it is 2, 1, 3, 4, because 24 orders exist and the list wraps. No search is needed, and the next-order rule is a short loop on the array.
Skip a repeat only at the same level. Skipping it everywhere loses bundles such as one and one.
Exercise · Put it in order: The next order. Arrange the lines into a function that rearranges an array of different numbers into the next order in dictionary order. After the last order it returns the first. Work in place and return the array.
def next_permutation(values):
i = len(values) - 2
while i >= 0 and values[i] >= values[i + 1]:
i -= 1
if i >= 0:
j = len(values) - 1
while values[j] <= values[i]:
j -= 1
values[i], values[j] = values[j], values[i]
values[i + 1:] = reversed(values[i + 1:])
return values
while i >= 0 and values[i] <= values[i + 1]:Solve them in this order. The first three choose items with rules. The next two arrange them. The last one needs no search at all.
Before each problem, write three lines: what a choice is, what rule is tested before it, and what makes two results the same. If the walk can reach the same result twice, decide how to skip it.
Give each problem about 25 minutes. Spend the first five on the three lines, and draw the first two levels of the search tree for a tiny input.
Three edge cases return on every rung. The empty choice often counts, such as the empty set. A single item gives one answer or none, so test it. And an input where every choice fails must return 0 and not crash.
When a solution gives too many results, find an input where the same result is reached twice. When it gives too few, find an input where a test cuts a branch that was valid.
When the count is slow, test the rule earlier, so that branches are cut near the root.
Checkpoint · Subsets and permutations
Q1/5 What is true of the partial answer at every step of the walk?
Answer: B
A choice is tested before it is made, so the partial answer never breaks a rule. A branch that would break one is cut.
Q2/5 Four packs have sizes 3, 2, 4 and 1. Packs 0 and 1 clash, and kept sizes total at most 6. How many valid sets are there, counting the empty one?
Answer: B
Of the 16 sets, the clash and the cap remove 7. That leaves 9 valid sets.
Q3/5 The coupons are 1, 1 and 2. How many different bundles are there?
Answer: B
There are 8 subsets by position, but {1} from either coupon is the same bundle, and so on. That gives 6 different bundles.
Q4/5 Riders wait in zones 0, 0, 1, 1 and 2. Why choose a zone, and not a rider, at each step?
Answer: B
Choosing a kind keeps a count per zone, so equal riders are never swapped to make a duplicate order.
Q5/5 A playlist is 1, 2, 3, 4. What is the order after 30 skips, if the list wraps round?
Answer: B
There are 24 orders, so 30 skips are 6 skips after the wrap. The order at position 6 is 2, 1, 3, 4.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.