1791. Grouped Card Listings
A card shop has n numbered cards, labelled 1 to n, and wants to sort them into exactly k non-empty display boxes. Return every possible grouping, where a grouping is a list of boxes and each box is the ascending list of card labels it holds.
To make the output unique, write the boxes of a grouping in order of their smallest card. Then give each grouping its growth string g, where g[i] is the 0-based index of the box that holds card i + 1. List the groupings in increasing lexicographic order of g. For n = 3 and k = 2 this gives [[1,2],[3]], then [[1,3],[2]], then [[1],[2,3]]. Build g left to right, letting each entry be at most one more than the largest entry before it, and stop a branch when too few cards remain to open k boxes. There are at most 90 groupings, and each takes O(n) to write out, so time is O(S(n,k) * n) with O(n) extra space.
Example 1
- Input:
- n = 3, k = 2
- Output:
- [[[1,2],[3]],[[1,3],[2]],[[1],[2,3]]]
- Explanation:
The three ways to split three cards into two boxes, in growth-string order 001, 010, 011, are listed.
Example 2
- Input:
- n = 4, k = 1
- Output:
- [[[1,2,3,4]]]
- Explanation:
With one box every card goes in it, so there is exactly one grouping.
Example 3
- Input:
- n = 4, k = 3
- Output:
- [[[1,2],[3],[4]],[[1,3],[2],[4]],[[1],[2,3],[4]],[[1,4],[2],[3]],[[1],[2,4],[3]],[[1],[2],[3,4]]]
- Explanation:
Choose which pair of cards shares a box; the 6 resulting groupings are listed in growth-string order.
Constraints
1 ≤ k ≤ n ≤ 6 (at most 90 partitions)
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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(S(n,k) * n)
- Space
- O(n)