leetcode(40) combination sum ii 解法

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

Each number in candidates 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.

Example 1:

1
2
3
4
5
6
7
8
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

Example 2:

1
2
3
4
5
6
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]

解法

这题只需要在Leetcode(39)上做一点点的改动,这里不允许一个数重复利用,故只需要将下一次搜索的起点改为i+1即可,同时考虑去除重复输出的情况,即在start之后进行分叉搜索时,若nums[i] = nums[i-1]时,说明已经考虑过了,直接进入下一次循环。

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class  {
List<List<Integer>> res = new ArrayList<>();

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

void helper(int[] candidates, int target, List<Integer> tmp, int start) {
if (target == 0) {
res.add(new ArrayList<>(tmp));
return;
} else if (target < 0) {
return;
} else {
for (int i = start; i < candidates.length && target >= candidates[i]; i++) {
if (i > start && candidates[i] == candidates[i - 1]) {
continue;
}
target = target - candidates[i];
tmp.add(candidates[i]);
helper(candidates, target, tmp, i + 1);
target = target + candidates[i];
tmp.remove(tmp.size() - 1);
}
}

}
}