Chat app~25 min2s · 256 MBtarget O(2^n) worst case, far less with pruning time, O(n) spaceclassic twin: lc-78backtracking
A chat app lets people keep sticker packs offline. Each pack has a size in kilobytes, and the phone has room for cap kilobytes in all.
Some pairs of packs share artwork and clash, so the app never keeps both of a clashing pair. Packs that do not clash with each other can be kept in any mix.
You count the different sets of packs that can be kept, including the empty set.
Write count_valid_bundles(sizes, clashes, cap).
sizes[i] is the size of pack i. The packs are numbered 0 to n - 1, where n = len(sizes).clashes[j] is [a, b]: packs a and b cannot both be kept. A clash is two-way, and a pack never clashes with itself.cap.Input: sizes = [4,3,5,2], clashes = [[0,2]], cap = 9
Output: 11The solution decides each pack in turn: leave it out, or keep it when it does not clash with a kept pack and still fits. Every full run of decisions that survives is one valid set.
| Valid set | Total size |
|---|---|
| empty | 0 |
{0} and {1} and {2} and {3} |
4, 3, 5 and 2 |
{0,1} and {1,2} |
7 and 8 |
{0,3} and {1,3} and {2,3} |
6, 5 and 7 |
{0,1,3} |
9 |
That is 1 + 4 + 2 + 3 + 1 = 11 sets. Four sets contain the clash between packs 0 and 2, and the set {1,2,3} has size 10, so those 5 sets are refused.
Input: sizes = [5], clashes = [], cap = 3
Output: 1The single pack is too big, so only the empty set is valid.
Input: sizes = [3,3], clashes = [], cap = 6
Output: 4Both packs together have size 6, which equals the cap, so all 4 sets are valid.
1 ≤ len(sizes) ≤ 22, and 1 ≤ sizes[i] ≤ 100,0000 ≤ len(clashes) ≤ 40, and every clash is [a, b] with 0 ≤ a, b < n0 ≤ cap ≤ 1,000,000,000Twenty-two packs have 2 to the power of 22 sets, which is 4,194,304. Checking every set costs about 22 steps for each, so about 92,000,000 steps. A search that stops at a clash or a full phone never builds those sets.