40. Combination Sum II

40. Combination Sum II


题目地址


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
32
33
34
35
36
37
38
39
40
41
List<List<Integer>> list = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
int[] tmp = new int[candidates.length];
//对candidates进行排序
Arrays.sort(candidates);
dfs(candidates, target, 0, 0, tmp, 0);
return list;
}


/**
* 该实现使用暴力遍历,但遍历过程剔除一层中一样的数据,这样就满足了不重复
*
* @param candidates 排序后的原始数组
* @param target 目标值
* @param k 当前的开始的第一个位置
* @param sum 遍历过的数据的和
* @param tmp 保存遍历过的数据
* @param dpth 记录遍历的深度
*/
private void dfs(int[] candidates, int target, int k, int sum, int[] tmp, int dpth) {
//System.out.println(dpth + "--"+sum+"===="+k);
if(sum==target) {
List<Integer> list2 = new ArrayList<>();
for(int i=0; i<dpth;i++) {
list2.add(tmp[i]);
}
//System.out.println(list2);
list.add(list2);
return ;
}
if(sum>target) {
return ;
}
for(int i = k; i<candidates.length; i++) {
tmp[dpth] = candidates[i];
dfs(candidates, target, i+1, sum+candidates[i], tmp, dpth+1);
while(i+1<candidates.length&&candidates[i]==candidates[i+1])i++;
}

}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×