Combinations of size k
Pick numbers moving forward only, so every combination shows up exactly once. About 8 minutes.
Pick forward, never back
Subsets asked "in or out" for every item. Combinations ask something subtler: which k numbers do you pick out of n? If you could add any number at any moment, then 1 and 3 would be counted as a different answer from 3 and 1, even though it is the same pair.
The fix is a starting point. Once you have looked at a number, you may only add numbers after it, like choosing seats in a row from left to right.
- curr
- [1]
Pick 1. The next pick starts from 2.
Stop at size k, not at the end of the range
There is no "reached the last number" base case here. You are not deciding in or out for every number; you are building a list until it holds exactly k of them.
As soon as the list has k entries, save a copy and return. The loop one level up carries on trying later numbers by itself.
res = []
def backtrack(start, curr):
if len(curr) == k:
res.append(list(curr))
return
for num in range(start, n + 1):
curr.append(num)
backtrack(num + 1, curr)
curr.pop()
backtrack(1, [])
return resWhy does the recursive call use backtrack(num + 1, curr) instead of backtrack(num, curr) or backtrack(0, curr)?
- ASo a number already tried is never tried again in this branch, and combinations can't be reordered into duplicates
- BIt's purely a speed optimization — starting from 0 would still give correct, just slower, results
- CIt marks the base case, the same way idx == n does for subsets
Show the answer
So a number already tried is never tried again in this branch, and combinations can't be reordered into duplicates. Moving start forward guarantees every combination is built with strictly increasing numbers, so each one is produced exactly once.
Combinations of size k
Given two integers n and k, return every combination of k numbers chosen from 1 to n, with no number repeated within a combination. List the numbers within each combination in increasing order, and list the combinations themselves in lexicographic order.
n = 4, k = 2 → [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
0 ≤ k ≤ n ≤ 10