Learn
Exam

Permutations with Repetition

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.
  • If multiple sets satisfy the above conditions, return the sets in lexicographical order.

Constraints

  • n is a natural number less than or equal to 8.
  • m is a natural number less than or equal to 8.

Test Case

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

Explanation for Test Case 1

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

Explanation for Test Case 2

  • From the integers 1, 2, 3, 4, and 5, selecting and arranging 1 number with repetition allowed produces the following 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 and 2, selecting and arranging 3 numbers with repetition allowed produces the following sets: [1,1,1], [1,1,2], [1,2,1], [1,2,2], [2,1,1], [2,1,2], [2,2,1], [2,2,2].
  • Sorting these sets lexicographically results in [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]].