Skip to content
BytePatterns

Choose K of the First N Numbers

EasyBacktracking#backtracking#combinations#pruning~15m

Problem

Given two integers n and k, return every way to choose k different numbers from 1 to n. Order inside a choice does not matter, so write each choice in ascending order, and return the choices in ascending lexicographic order.

Examples

Input:  n = 4, k = 2
Output: [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
Why:    4 choose 2 is 6
Input:  n = 3, k = 3
Output: [[1, 2, 3]]
Why:    there is only one way to take everything
Input:  n = 2, k = 0
Output: [[]]
Why:    edge case, choosing nothing is exactly one choice, the empty one

Hints

0 / 3

Stuck on the idea rather than the code? Subsets covers it.