https://leetcode.com/problems/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]
]
1 class Solution {
2 public List<List<Integer>> combinationSum2(int[] candidates, int target) {
3 List<List<Integer>> res = new ArrayList<>();
4 if (candidates == null || candidates.length ==0) {
5 return res ;
6 }
7 //去重复,选代表必须要做的
8 Arrays.sort(candidates);
9 List<Integer> sol = new ArrayList<>();
10 dfs(candidates, target, 0, res, sol);
11 return res ;
12 }
13
14 private void dfs(int[] candidates, int remain,int start, List<List<Integer>> res, List<Integer> sol){
15 //terminate condition
16 if (remain <= 0) {
17 if (remain == 0) {
18 res.add(new ArrayList(sol));
19 }
20 return;
21 }
22 for (int i = start ; i < candidates.length; i++) {
23 // 1 1' 1'' 结果 [1 1'] 和 [1 1‘’] 是一样的,后者跳过
24 if (i>0 && candidates[i] == candidates[i-1] && i>start) {
25 continue ;
26 }
27 sol.add(candidates[i]);
28 //因为一个元素职能用一次,所以必须+1
29 dfs(candidates, remain-candidates[i], i+1, res, sol);
30 sol.remove(sol.size()-1);
31 }
32 }
33 }