Combination Sum

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.

The same repeated number may be chosen from C unlimited number of times.

Important:

  • 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.

Example:

given candidate set 2,3,6,7 and target 7, a solution set is:

[ 
  [7], 
  [2, 2, 3]
]

given 3, 2, 2 and target 7, the solution

[
  [2, 2, 3]
]

Solution:

Similar to Subsets problem. We could use depth first search to solve it.

Code:

public class Solution {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        List<Integer> list = new ArrayList<>();
        Arrays.sort(candidates);
        recHelper(candidates, target, 0, list, res);
        return res;
    }

    private void recHelper(int[] candidates, int target, int index,
                    List<Integer> list, List<List<Integer>> res) {
        if (target == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        int prev = Integer.MIN_VALUE;
        for (int i = index; i < candidates.length; i++) {
            if (prev == candidates[i]) {
                continue;
            }
            if (target < candidates[i]) {
                continue;
            }
            list.add(candidates[i]);
            recHelper(candidates, target - candidates[i], i, list, res);
            list.remove(list.size() - 1);
            prev = candidates[i];
        }
    }
}

results matching ""

    No results matching ""