Combinations

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:

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> ans = new ArrayList<>();
        combine(ans, n, k, 0, new ArrayList<Integer>());
        return ans;
    }
    public void combine(List<List<Integer>> ans, int n, int k, int start, List<Integer> list){
        if(k==0){
            ans.add(new ArrayList<>(list));
            return;
        }
        for(int i=start; i<n; i++){
            list.add(i+1); /* count from 1 */
            combine(ans, n, k-1, i+1, list);
            list.remove(list.size()-1);
        }
    }
}
comments powered by Disqus