Practice › Recursion & Backtracking
All Combinations of K from N
Medium · Recursion & Backtracking · Asked at Amazon, Google, Microsoft, Adobe
Print every way to choose k different numbers from 1 … n, each choice in increasing order, and all choices in lexicographic order, one per line.
Input
A single line with n and k.
Output
The combinations, one per line.
Constraints
- 1 ≤ k ≤ n ≤ 12
Backtrack: choose the next number from just after the last one chosen. Prune when there are not enough numbers left to reach k.
Example 1
Input
4 2
Output
1 2 1 3 1 4 2 3 2 4 3 4
Example 2
Input
1 1
Output
1
Hints
- Build each combination in increasing order, so the next number is always larger than the last.
- Trying numbers in increasing order gives lexicographic order automatically.
- Stop early when the remaining numbers cannot fill the combination.
Approach
go(start): if k numbers are chosen, print them. Otherwise, for x from start up to n − (k − chosen) + 1, choose x and recurse with start = x + 1. The upper bound prunes branches that could never reach k numbers.
Complexity: O(C(n, k) · k) time · O(k) recursion depth
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int n, k;
vector<int> cur;
string out;
void go(int start) {
if ((int) cur.size() == k) {
for (int i = 0; i < k; i++) out += to_string(cur[i]) + (i + 1 < k ? " " : "\n");
return;
}
for (int x = start; x <= n - (k - (int) cur.size()) + 1; x++) {
cur.push_back(x);
go(x + 1);
cur.pop_back();
}
}
int main() {
cin >> n >> k;
go(1);
cout << out;
return 0;
}Python solution
n, k = map(int, input().split())
cur, out = [], []
def go(start):
if len(cur) == k:
out.append(" ".join(map(str, cur)))
return
for x in range(start, n - (k - len(cur)) + 2):
cur.append(x)
go(x + 1)
cur.pop()
go(1)
print("\n".join(out))Java solution
import java.util.*;
public class Main {
static int n, k;
static int[] cur;
static StringBuilder out = new StringBuilder();
static void go(int start, int depth) {
if (depth == k) {
for (int i = 0; i < k; i++) out.append(cur[i]).append(i + 1 < k ? " " : "\n");
return;
}
for (int x = start; x <= n - (k - depth) + 1; x++) {
cur[depth] = x;
go(x + 1, depth + 1);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
cur = new int[k];
go(1, 0);
System.out.print(out);
}
}Solve All Combinations of K from N online · All practice problems