Friday, June 9, 2017

39. Combination Sum

Given a set of candidate numbers (C(without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T
The same repeated number may be chosen from C unlimited number of times.
Note:
  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 
[
  [7],
  [2, 2, 3]
]



Solution:

Use DFS to traverse all combinations and check if the sum is target.

To remove duplicates, we first sort the array.

In the DFS function, when we find a number equals to its previous one but the previous one has not been selected, we cannot select this number.



Code:


public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return result;
        }
        Arrays.sort(candidates);
        helper(candidates, target, result, new ArrayList<Integer>(), 0);
        return result;
    }
    
    public void helper(int[] nums, int target, List<List<Integer>> result, List<Integer> list, int pos) {
        if (target == 0) {
            result.add(new ArrayList<Integer>(list));
            return;
        }
        if (target < 0) {
            return;
        }
        for (int i = pos; i < nums.length; i++) {
            if (i != pos && nums[i] == nums[i - 1]) {
                continue;
            }
            list.add(nums[i]);
            helper(nums, target - nums[i], result, list, i);
            list.remove(list.size() - 1);
        }
    }
}