Recursion and Backtracking Generating every choice
326. Combinations
You are given two integers n and k. Return every combination of k different numbers chosen from the
numbers 1 to n.
A combination is a choice of numbers in which order does not matter, so [1,3] and [3,1] are the same
combination and you return it once. A combination never uses the same number twice.
The combinations can come back in any order, and so can the numbers inside each one. Any order is accepted. The examples list each combination's numbers from smallest to largest and sort the combinations.
Example 1
Input: n = 5, k = 3
[[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 ten ways to choose three of the numbers 1 to 5. Six of them use 1, three more use 2 but not 1,
and [3,4,5] uses neither.
Example 2
Input: n = 4, k = 1
[[1],[2],[3],[4]]Explanation: With one number to choose, each number from 1 to 4 is a combination on its own.
Example 3
Input: n = 3, k = 3
[[1,2,3]]Explanation: When k equals n, the only combination takes every number.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ k ≤ n ≤ 20
Clarifying questions
What you would ask an interviewer before writing any code.