Thursday, November 6, 2014

Facebook: Combinations (n, k)

Combinations (n, k) -- print all combinations of k out of n items
public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if (n <= 0 || k <= 0 || n < k) {
            return result;
        }
        
        int[] num = new int[n];
        for (int i = 0; i < n; i++) {
            num[i] = i + 1;
        }
        
        List<Integer> curr = new ArrayList<Integer>();
        combineHelper(num, k, 0, 0, curr, result);
        
        return result;
    }
    
    private void combineHelper(int[] num, int k, int start, int count, List<Integer> curr, List<List<Integer>> result) {
        if (count == k) {
            result.add(new ArrayList<Integer>(curr));
            return;
        }
        
        for (int i = start; i < num.length; i++) {
            curr.add(num[i]);
            combineHelper(num, k, i + 1, count + 1, curr, result);
            curr.remove(curr.size() - 1);
        }
    }
}

Note that we don't need to check start > num.length here because we have guaranteed that k <= n. That is an error-prone point for combination problem.

No comments:

Post a Comment