leetcode

Combination Sum II

Given a set 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, 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]

Same idea as Combination Sum, use a previous variable to track previous element in the array to avoid duplicate results, also do not add the current element in the next recursion.

public List<List<Integer>> combinationSum2(int[] num, int target) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        if (num==null||num.length==0) {
            return results;
        }
        Arrays.sort(num);

        combinationSum2(results, new ArrayList<Integer>(), 0, num, target, 0);

        return results;
    }

    public void combinationSum(List<List<Integer>> results, List<Integer> result, int sum, int[] num, int target, int level) {
        if (sum>target) {
            return;
        }

        if (sum==target) {
            List<Integer> solution = new ArrayList<Integer>(result);
            results.add(solution);
            return;
        }

        //since the passed num is sorted, use one previous value to track already added value to avoid duplicate solution
        int previous = -1;
        for (int i=level; i<num.length; i++) {
            //why do we want to use previous? For example [1,1,2,5,6,7], 
            // we do not want to recalculate the second 1 since the first 1 is already calculated
            if (num[i]!=previous) {
                result.add(num[i]);
                sum+=num[i];
                combinationSum2(results, result, sum, num, target, i+1);
                previous = num[i];
                sum-=num[i];
                result.remove(result.size()-1);
            }            
        }
    }