Algo-Sim › Recursion & Backtracking
Combinations
Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input
Every k-number subset of 1..n: add numbers in increasing order, and prune a branch once too few numbers remain.
Problem
Given n and k, return every way to choose k different numbers from 1..n. Order inside a combination does not matter, so [1, 2] and [2, 1] are the same.
Constraints
- 1 ≤ n ≤ 20
- 1 ≤ k ≤ n
Edge cases to test
- k = 0:
[[]] - k = n: one combination
- k = 1
Follow-up questions
- How much does the pruning save?
- Stopping when fewer than
k − sizenumbers remain cuts every dead branch, so the work is O(k·C(n, k)). - Is there an iterative way?
- Gosper’s hack walks all k-bit masks in increasing order for n ≤ 64.
Solution
Java
List<List<Integer>> result = new ArrayList<>();
List<List<Integer>> combine(int n, int k) {
backtrack(n, k, 1, new ArrayList<>());
return result;
}
void backtrack(int n, int k, int start, List<Integer> path) {
if (path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for (int i = start; i <= n; i++) {
if (n - i + 1 < k - path.size()) break;
path.add(i);
backtrack(n, k, i + 1, path);
path.remove(path.size() - 1);
}
}Python
def combine(n, k):
result = []
def backtrack(start, path):
if len(path) == k:
result.append(path[:])
return
for i in range(start, n + 1):
if n - i + 1 < k - len(path):
break
path.append(i)
backtrack(i + 1, path)
path.pop()
backtrack(1, [])
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> result = {};
vector<vector<int>> combine(int n, int k) {
vector<int> path;
backtrack(n, k, 1, path);
return result;
}
void backtrack(int n, int k, int start, vector<int> &path) {
if (int(path.size()) == k) {
result.push_back(path);
return;
}
for (int i = start; i <= n; i++) {
if (n - i + 1 < k - int(path.size()))
break;
path.push_back(i);
backtrack(n, k, i + 1, path);
path.pop_back();
}
}
};
More Recursion & Backtracking problems
- Fibonacci Number (Easy)
- Tower of Hanoi (Medium)
- Generate Parentheses (Medium)
- Subsets (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Permutations II (Medium)
- Letter Combinations of a Phone Number (Medium)
- Combination Sum (Medium)
- Combination Sum II (Medium)
- Palindrome Partitioning (Medium)
- Restore IP Addresses (Medium)
- Word Break II (Hard)
- Remove Invalid Parentheses (Hard)
- Word Search (Medium)
- N-Queens (Hard)
- Sudoku Solver (Hard)