77. Combinations

Problem:

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

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Solution:

 public List<List<Integer>> combine(int n, int k) {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    combines(ans, new ArrayList<Integer>(), 1, n, k);
    return ans;
}
public void combines(List<List<Integer>> ans, List<Integer> comb, int start, int n, int k){
    if(k == 0){
        ans.add(new ArrayList<Integer>(comb));
        return;
    }
    for(int i = start; i <= n; i++){
        comb.add(i);
        combines(ans, comb, i + 1, n, k - 1);
        comb.remove(comb.size() - 1);
    }
}

Last updated

Was this helpful?