1781. Rival-Free Seating
A banquet host seats n guests, numbered 0 to n - 1, in a single row of n chairs. Some pairs of guests are rivals: each entry [u, v] of rivals says guests u and v refuse to sit in neighbouring chairs, in either order.
Return the number of different seating orders (permutations of all guests along the row) in which no rival pair sits side by side. Two orders are different if some chair holds a different guest. Return 1 when n = 1. The answer can exceed 32 bits for the larger inputs, so return a 64-bit integer. Listing every order is too slow for n = 12; use a bitmask DP over the set of seated guests and the last guest seated, with each guest's rivals stored as a mask. Intended complexity: O(2^n * n^2) time and O(2^n * n) space.
Example 1
- Input:
- n = 3, rivals = [[0,1]]
- Output:
- 2
- Explanation:
Guests 0 and 1 may not be neighbours, so only the orders 0-2-1 and 1-2-0 work and the answer is 2.
Example 2
- Input:
- n = 4, rivals = [[0,1],[2,3]]
- Output:
- 8
- Explanation:
Of the 24 orders, 8 put 0 and 1 together, 8 put 2 and 3 together and 4 do both, so 24 - 8 - 8 + 4 = 12.
Constraints
1 ≤ n ≤ 12
0 ≤ rivals.length ≤ 30
rivals[i] = [u, v], 0 ≤ u, v < n, u ≠ v, and all pairs are distinct (as unordered pairs)
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(2^n * n^2)
- Space
- O(2^n * n)