1819. Perfect Cover Selections

Hard7.5 points estimatedBacktrackingBitmaskRecursion

A catering planner has m dishes numbered 0 to m-1 and a list of packages. Package i is described by the bitmask options[i], where bit j is set when the package contains dish j. Count how many sets of packages together contain every dish exactly once, so no dish is missing and no dish is repeated. Packages with identical masks at different indices are different packages and count separately, and a set is unordered. Return the count as a long.

Branch on the dish that currently has the fewest compatible packages, try each of those packages, and cache the result by the mask of dishes already covered, since the number of completions depends on that mask alone. If some dish has no compatible package the branch contributes 0.

Example 1

Input:
m = 4, options = [3,12,5,10,15]
Output:
3
Explanation:

Masks 3+12, 5+10 and 15 alone are the three exact covers of the four dishes.

Example 2

Input:
m = 3, options = [1,2,4]
Output:
1
Explanation:

Only the three single-dish packages together cover every dish exactly once.

Example 3

Input:
m = 2, options = [1,1,2,2]
Output:
4
Explanation:

Each dish can use either of its two identical packages, so 2 * 2 = 4 selections.

Constraints

1 ≤ m ≤ 20

1 ≤ options.length ≤ 40

1 ≤ options[i] < 2^m

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(S * options), S = reachable masks
Space
O(S)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…