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

Edge cases to test

Follow-up questions

How much does the pruning save?
Stopping when fewer than k − size numbers 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 result

C++

#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