Every way to choose k numbers from 1 to n. Pick the next number only from those after the last pick, recurse, then undo the pick and try the next.
▼The problem
LeetCode 77 (Medium). Given two integers n and k, return all possible combinations of k numbers chosen from the range 1..n, in any order.
Examples (LeetCode's): n = 4, k = 2 → [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]], n = 1, k = 1 → [[1]].
The solution
def combine(n, k):
res, path = [], []
def back(start):
if len(path) == k:
res.append(path[:])
return
last = n - (k - len(path)) + 1
for i in range(start, last + 1):
path.append(i)
back(i + 1)
path.pop()
back(1)
return resTranscript
Combinations. You're given two numbers, n and k. Return every way to choose k numbers from one to n. Order doesn't matter: one, two and two, one are the same team.
Take n equals four and k equals two: four penguins and a sled with two seats. There are six teams: one two, one three, one four, two three, two four, and three four. With n one and k one, the only answer is one.
The direct way builds every subset and keeps the ones of size k. For four numbers, that's two to the fourth: sixteen subsets built, six kept, ten wasted. With twenty numbers and k of three, it builds over a million subsets to keep just one thousand one hundred forty.
Instead, only build teams that can work. Backtrack with a start index. Pick a number from start onward, put it on the path, then recurse with start just past it. Numbers only go up, so there are no duplicates and no reorderings. When the path holds k numbers, record a copy. It's Subsets, stopped at size k.
And prune. If the path still needs two numbers, four can't come first: nothing is left after it. So the loop stops at n, minus the numbers still needed, plus one. For four and two, that's three.
In code: if the path has k numbers, save a copy and return. Otherwise, work out the last useful start, and loop from start to last. Append the number, recurse from the next one, then pop it off.
Now four and two. Pick one, then two: full, record one two. Pop two and try three: one three. Then one four. Pop one, and pick two: two three, two four. Then pick three: three four. Four is never picked first. Six teams.
There are n choose k answers, and copying each costs k, so the time is order k times n choose k. The path and the recursion are only k deep: order k extra space.
Pick, recurse, unpick. That's Combinations.