Search This Blog

Wednesday, December 26, 2012

LeetCode: Combination Sum II

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] 
» Solve this problem

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
        // Start typing your Java solution below
        // DO NOT write main() function
        Arrays.sort(num);
        ArrayList<ArrayList<Integer>> prev = new ArrayList<ArrayList<Integer>>();
        prev.add(new ArrayList<Integer>());
        return combinationSum(num,target,0,prev);
    }
    
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target, int i, ArrayList<ArrayList<Integer>> prev){
        ArrayList<ArrayList<Integer>> res = new  ArrayList<ArrayList<Integer>>();
        if(target==0){
            for(ArrayList<Integer> temp:prev){
                ArrayList<Integer> temp1 = new ArrayList<Integer>(temp);   
                res.add(temp1);
            }    
            return res;
        }    
        for(int j=i;j<candidates.length;j++){
            if(candidates[j]>target)
                break;
            if(j==i || candidates[j]!=candidates[j-1]){    
                for(ArrayList<Integer> temp:prev)
                    temp.add(candidates[j]);    
                ArrayList<ArrayList<Integer>> next = combinationSum(candidates,target-candidates[j],j+1,prev);
                if(next.size()>0)
                    res.addAll(next);
                for(ArrayList<Integer> temp:prev)
                    temp.remove(temp.size()-1);
            }
        }
        return res;
    }
}

No comments: