1776. Spaced Combinations
A festival organiser must choose k booth slots from the numbered slots 1 to n along a street. To avoid crowding, any two chosen slots must differ by at least gap, so slots 2 and 5 are fine for a gap of 3 but 2 and 4 are not.
Return every selection of exactly k slots that satisfies the spacing rule. Each selection is an ascending array of k numbers and the selections are listed in lexicographic order. If no selection exists, return an empty list. Use backtracking: when left numbers still have to be chosen and the next candidate is next, prune as soon as next + (left - 1) * gap > n, because the remaining numbers could no longer fit. The inputs guarantee at most 300 selections, so the running time is proportional to the output, O(k * answer) with O(k) extra space.
Example 1
- Input:
- n = 5, k = 2, gap = 2
- Output:
- [[1,3],[1,4],[1,5],[2,4],[2,5],[3,5]]
- Explanation:
Pairs from 1..5 whose members differ by at least 2 are listed in lexicographic order.
Example 2
- Input:
- n = 6, k = 3, gap = 2
- Output:
- [[1,3,5],[1,3,6],[1,4,6],[2,4,6]]
- Explanation:
Only four triples from 1..6 keep every neighbouring gap at 2 or more.
Example 3
- Input:
- n = 4, k = 1, gap = 1
- Output:
- [[1],[2],[3],[4]]
- Explanation:
With k = 1 every single slot is its own selection.
Constraints
1 ≤ k ≤ 5; k ≤ n ≤ 20; 1 ≤ gap ≤ n; inputs guarantee at most 300 combinations.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(k * C)
- Space
- O(k)