Combination Sum II(Medium)

Leetcode Source

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:

  1. All numbers (including target) will be positive integers.
  2. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  3. 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]

解题思路:回溯+DFS

时间复杂度O(n!),空间复杂度O(n)

public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> result = new LinkedList<List<Integer>>();

    if(candidates == null || candidates.length == 0)
        return result;

    List<Integer> current = new LinkedList<Integer>();;
    Arrays.sort(candidates);

    combinationSum(candidates, target, 0, current, result);

    return result;
}

public void combinationSum(int[] candidates, int target, int start, List<Integer> curr, List<List<Integer>> result){
    if(target == 0){
        List<Integer> temp = new LinkedList<Integer>(curr);
        result.add(temp);
        return;
    }

    for(int i=start; i<candidates.length; i++){
        //instead of getting next element right away, we get the element with different value.
        //确保candidates[i]最多只用一次, remove duplicate list
        if (i > start && candidates[i] == candidates[i - 1]) {
            continue;
        }

        if(target < candidates[i])
            return;

        curr.add(candidates[i]);
        combinationSum(candidates, target - candidates[i], i+1, curr, result);
        curr.remove(curr.size()-1);
    }
}

results matching ""

    No results matching ""