Monday, March 24, 2014

Leetcode: Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

Solution

public class Solution {
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        List<List<Integer>> solution = new ArrayList<List<Integer>>();
        Arrays.sort(num);
        combinationSum2(num, target, 0, 0, new ArrayList<Integer>(), solution);
        return solution;
    }
    
    public void combinationSum2(int[] num, int target, int index, int currentSum, ArrayList<Integer> current,  List<List<Integer>> solution)
    {
        if(currentSum == target)
        {
            solution.add((ArrayList<Integer>)current.clone());
            return;
        }
        for(int i=index; i< num.length; i++)
        {
            if((i==index || num[i-1]<num[i]) && currentSum+num[i]<=target)
            {
                current.add(num[i]);
                combinationSum2(num, target, i+1, currentSum+num[i], current,  solution);
                current.remove(current.size()-1);
            }
        }
        
    }
}

No comments :

Post a Comment