Wednesday, January 7, 2015

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 (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ 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 List<List<Integer>> result;
    private List<Integer> x;
    private int sum;
    
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        // Backtracking problem
        // Firstly, sort num array
        result = new LinkedList<>();
        int n = num.length;
        
        if (n == 0)
            return result;
            
        Arrays.sort(num);
        
        x = new LinkedList<>();
        
        for (int i = 0; i < n; i++)
        {
            if (i==0 || num[i]>num[i-1]) // Avoid duplicates
            {
                x.clear();
                sum = 0;
                backTracking(num, target, i);
            }
        }
        
        return result;
    }
    
    private void backTracking(int[] num, int target, int cnt)
    {
        x.add(num[cnt]);
        sum += num[cnt];
                
        if (sum < target)
            for (int i = cnt+1; i < num.length; i++)
                backTracking(num, target, i);
        else if (sum == target)
        {
            List<Integer> ret = new LinkedList<>(x);
            
            if (!result.contains(ret)) // Avoid duplicates
                result.add(ret);
        }
            
        x.remove(x.size()-1);   
        sum -= num[cnt];
    }
}

No comments:

Post a Comment