Leetcode 40. Combination Sum II

Description:

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:

  • All numbers (including target) will be positive integers.
  • 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]
]

Thinking:

We need use the combination template, but we should notice the difference between the combination sum I that collection can let duplicated number exit. So we need to sort the array. And we can only one number only one time.

Complexity:

The time complexity is n!;

Step:

  1. Check whether input is valid.
  2. Create helper function and decide return condition.

Code:

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

Conclusion:

how to skip the duplicated number, we often use the format like if( i == pos || (i >0 && nums[i] != nums[i-1]))

results matching ""

    No results matching ""