Combinations Problem
Description
LeetCode Problem 77.
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Constraints:
- 1 <= n <= 20
- 1 <= k <= n
Solution
Approach: Backtracking
We build each combination one number at a time, always in increasing order, so the same set is never produced twice (we get [1, 2] but never [2, 1]).
backtrack(start) extends the current combination using only numbers from start to n:
- If the combination already has
knumbers, save a copy of it and return. - Otherwise, for each
numberfromstartupwards: add it, callbacktrack(number + 1)to choose the rest from larger numbers, then remove it again (undo the choice) and try the next one.
The answer is backtrack(1).
Two details:
- Save a copy. The current combination keeps changing as we undo choices, so storing the list itself would leave every saved entry pointing at the same (finally empty) list.
- Prune. If we still need
still_needednumbers, the next one can be at mostn - still_needed + 1; any larger number leaves too few numbers to finish. Stopping the loop there skips every dead branch.
For n = 4, k = 2, the calls produce [1,2], [1,3], [1,4], [2,3], [2,4], [3,4], and the loop for the first number stops at 3.
Complexity: O(k · C(n, k)) time, since there are C(n, k) combinations and copying each takes O(k), and O(k) extra space for the recursion and the current combination (not counting the output).
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
combinations = []
current = [] # the combination being built, in increasing order
def backtrack(start: int) -> None:
if len(current) == k:
combinations.append(current[:]) # store a copy: current keeps changing
return
still_needed = k - len(current)
# Stop early when fewer than still_needed numbers are left after this one.
for number in range(start, n - still_needed + 2):
current.append(number)
backtrack(number + 1)
current.pop() # undo the choice and try the next number
backtrack(1)
return combinations
Now write it from memory
Close the write-up and solve it yourself against the tests.