/77. Combinations

77. Combinations

Medium
Backtracking74.3% acceptance

Given two integers upper_bound and selection_size, return all possible subsets of selection_size distinct integers chosen from the range [1, upper_bound]. Each subset must contain exactly selection_size elements, and the order of elements within each subset does not matter. Return the list of subsets in any order.

Example 1

Input: upper_bound=5, selection_size=3

Output: [[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]]

Explanation: There are 10 possible combinations of 3 numbers from 1 to 5.

Example 2

Input: upper_bound=3, selection_size=1

Output: [[1],[2],[3]]

Explanation: Each single number from 1 to 3 forms a combination.

Constraints

  • 1 <= upper_bound <= 20
  • 1 <= selection_size <= upper_bound
Python (current runtime)

Case 1

Input: upper_bound=6, selection_size=2

Expected: [[1,2],[1,3],[1,4],[1,5],[1,6],[2,3],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6],[4,5],[4,6],[5,6]]

Case 2

Input: upper_bound=2, selection_size=2

Expected: [[1,2]]

Case 3

Input: upper_bound=4, selection_size=1

Expected: [[1],[2],[3],[4]]