LeetCode 40. Combination Sum II

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]
]

题意:这题和上一题39题,简直一模一样,那道题是可以重复的应用同一个位置的数字,这题是不允许重复的应用同一个位置的数字。

只需要在上一题的基础上,递归的时候每次都大1,即不能等于本身就可以了。

java代码:

public List> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List> result = new ArrayList>();
        getResult(result, new ArrayList(), candidates, target, 0);
        return result;
    }

    public void getResult(List> result, List current, int[] candiates, int target, int start) {
        if (target > 0) {
            for (int i = start; i < candiates.length && target >= candiates[i]; i++) {
                current.add(candiates[i]);
                getResult(result, current, candiates, target - candiates[i], i + 1);
                current.remove(current.size() - 1);
            }
        } else if (target == 0) {
            if (!result.contains(current)) {
                result.add(new ArrayList(current));
            }
        }
    }

你可能感兴趣的:(LeetCode 40. Combination Sum II)