Wednesday, February 12, 2014

Leetcode: 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 ArrayList<ArrayList<Integer>> combine(int n, int k) {
        ArrayList<ArrayList<Integer>> solution = new ArrayList<ArrayList<Integer>>();
        combine(1, n, k, new int[k],  solution);
        return solution;
    }
    
    public void combine(int start, int end, int numbersLeft, int[] partial, ArrayList<ArrayList<Integer>> solution) 
    {
        if (numbersLeft==0)
        {
            ArrayList<Integer> temp = new ArrayList<Integer>();
            for(int k=0; k<partial.length; k++) temp.add(partial[k]); 
            solution.add(temp);
            return;
        }
        
        for(int i=start; i<=end-numbersLeft+1; i++)
        {
            partial[partial.length-numbersLeft] = i;
            combine(i+1, end, numbersLeft-1, partial,  solution);    
        }
    }
}

No comments :

Post a Comment