Learn
Exam

Permutations

Difficulty
INTERMEDIATE

Problem

Given two natural numbers n and m, write a solution function that returns all sets of m numbers selected from the integers between 1 and n that satisfy the following conditions:

Conditions:

  • Each set contains exactly A1,A2,⋯ ,AmA_1, A_2, \cdots, A_m numbers.
  • 1≤A1,A2,⋯ ,Am≤n1 \leq A_1, A_2, \cdots, A_m \leq n.
  • For any ii and jj are not equal, AiA_i and AjA_j are also not equal.
  • If multiple sets satisfy the above conditions, return the sets in lexicographical order.

Constraints

  • n is a natural number between 3 and 10.
  • m is a natural number less than or equal to n.

Test Case

Test Case Number n m return
1 4 2 [[1,2],[1,3],[1,4],[2,1],[2,3],[2,4],[3,1],[3,2],[3,4],[4,1],[4,2],[4,3]]
2 5 1 [[1],[2],[3],[4],[5]]
3 3 3 [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Explanation for Test Case 1

  • From the integers 1, 2, 3, and 4, selecting and arranging 2 numbers produces the following 12 sets: [1,2], [1,3], [1,4], [2,1], [2,3], [2,4], [3,1], [3,2], [3,4], [4,1], [4,2], [4,3].
  • Sorting these sets lexicographically results in [[1,2],[1,3],[1,4],[2,1],[2,3],[2,4],[3,1],[3,2],[3,4],[4,1],[4,2],[4,3]].

Explanation for Test Case 2

  • From the integers 1, 2, 3, 4, and 5, selecting and arranging 1 number produces the following 5 sets: [1], [2], [3], [4], [5].
  • Sorting these sets lexicographically results in [[1],[2],[3],[4],[5]].

Explanation for Test Case 3

  • From the integers 1, 2, and 3, selecting and arranging 3 numbers produces the following 6 sets: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].
  • Sorting these sets lexicographically results in [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]].