LeetCode 77. Combinations

Problem:

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Solution:

Backtracking

public class Solution {
    List<List<Integer>> all;
    public List<List<Integer>> combine(int n, int k) {
        all = new ArrayList<List<Integer>>();
        List<Integer> option = new ArrayList<Integer>();
        choose(1, n, k, option);
        return all;
    }
    
    private void choose(int start, int n, int k, List<Integer> option) {
        if (k == 0) {
            List<Integer> copy = new ArrayList<Integer>(option);
            all.add(copy);
            return;
        }
        for (int i = start; i <= n - k + 1; i++) {
            option.add(i);
            choose(i+1, n, k-1, option);
            option.remove(option.size() - 1);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *