Combination Sum

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.

For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]

Example

given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]

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.

Solution: Subsets 变种题 DFS

O(2^n) time

public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> result = new ArrayList<>();
    if (candidates == null) {
        return result;
    }
    Arrays.sort(candidates);
    combinationSumHelper(new ArrayList<Integer>(), 0, candidates, target, result);

    return result;
}

public void combinationSumHelper(ArrayList<Integer> curr, int index, int[] candidates, int target, List<List<Integer>> result) {
    if (target == 0) {
        result.add(new ArrayList<>(curr));
        return;
    }
    if (index >= candidates.length) {
        return;
    }
    for (int i = index; i < candidates.length; i++) {
        if (candidates[i] <= target) {
            curr.add(candidates[i]);
            combinationSumHelper(curr, i, candidates, target - candidates[i], result);
            curr.remove(curr.size() - 1);
        }
    }
}
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *