40 Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations inCwhere the candidate numbers sums toT.

Each number inCmay only be usedoncein 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 target8,
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

分析及代码

和39几乎是一样的,但是因为candidates里面有重复的数字,比如说例子里面的[1,2,5],如果不处理,那么会根据candidates里面两个1给出两组长的一样的解

方法就是先sort一下,如果遇到index开始以后的数,并且和前一个是相同的就跳过

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        if(candidates.length == 0) {
            return res;
        }
        Arrays.sort(candidates);
        generator(res, new ArrayList<>(), candidates, target, 0);
        return res;
    }

    private void generator(List<List<Integer>> res, List<Integer> item, int[] candidates, int remain, int index) {
        if(remain < 0) {
            return;
        }
        if(remain == 0) {
            res.add(new ArrayList<>(item));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            if(i > index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            item.add(candidates[i]);
            generator(res, item, candidates, remain - candidates[i], i + 1);
            item.remove(item.size() - 1);
        }
    }

O(2^n)不变

results matching ""

    No results matching ""