Tuesday, April 12, 2016

[LeetCode] 40. 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]
public class Solution {
    
    private void combinationSumAux(int[] candidates, int target, int i, int sum, List path, List> res){
               
        // because of your recursive call structure, result judgement has to come before boarder i == candicates.length
        if(sum == target){
            res.add(new ArrayList(path)); 
            return;
        }
       
        if(i == candidates.length)
            return; 
            
        if(sum > target)
            return;
        
        int n = candidates[i];
        
        int k = i+1;
        
        // Error: Note here, [1, 1], we have to ignore the repeating numbers when we decide to not use any one of them.
        while(k < candidates.length && candidates[k] == candidates[k-1]){
            ++k;
        }
        combinationSumAux(candidates, target, k, sum, path, res);
                
        sum += n;
        path.add(n);
        combinationSumAux(candidates, target, i+1, sum, path, res);
        sum -= n;
        path.remove(path.size()-1);
        
        return;
        
    }
    
    public List> combinationSum2(int[] candidates, int target) {
        int len = candidates.length;
        
        List> ret = new ArrayList>();
        
        if(0 == len)
            return ret;
            
        Arrays.sort(candidates);
            
        List path = new ArrayList();
            
        combinationSumAux(candidates, target, 0, 0, path, ret);
        
        return ret;
    }
}

No comments:

Post a Comment