Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n]. You may return the answer in any order.
n = 4, k = 2[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]n = 1, k = 1[[1]]Standard k-combination backtracking. The pruning bound n-(k-curr.size)+1 avoids branches that can never reach k elements — if fewer candidates remain than needed, stop early. Since we go in ascending order (start=i+1), no duplicate combinations arise.
Generating every subset and keeping those of size k wastes work. Stop as soon as a path has k numbers.
Choose numbers in increasing order, starting after the last one picked. When the path has k numbers, record it and return. Prune: if too few numbers are left to reach k, stop the loop early.
Increasing order avoids repeats. Prune when not enough numbers are left.
Run the animation above on your own input, or watch the 1:15 video explanation of Combinations with a dry run and Java code.