Combinations: Generate All nCr
Aldbourne Hospital draws up the on-call rota by listing every possible team. Staff are numbered 1 upwards, a team is a fixed size, and nobody can be on a team twice. Two teams made of the same people are the same team no matter what order the names were written in, so each team is listed once, with its numbers rising from left to right. The whole list is printed in dictionary order so the rota committee can work down it.
Task: Print every possible team.
Input
A single line holding two integers separated by a space: n, the number of staff, who are numbered 1 to n; then r, the team size. Both are between 1 and 12, and r is never larger than n.
Output
One team per line, its r numbers separated by single spaces and rising from left to right. Every team of r different staff must appear exactly once. Lines come out in dictionary order: compare two lines by their first number, then their second where those tie, and so on.
Example:
Input:
4 2
Output:
1 2
1 3
1 4
2 3
2 4
3 4
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in