-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombinationSum2.java
More file actions
executable file
·80 lines (65 loc) · 2.23 KB
/
combinationSum2.java
File metadata and controls
executable file
·80 lines (65 loc) · 2.23 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package backtracking;
import array.LIS;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 给定候选号码数组 (C) 和目标总和数 (T),找出 C 中候选号码总和为 T 的所有唯一组合。
C 中的每个数字只能在组合中使用一次。
注意:
所有数字(包括目标)都是正整数。
解决方案集不能包含重复的组合。
例如,给定候选集合 [10, 1, 2, 7, 6, 1, 5] 和目标总和数 8,
可行的集合是:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
* Created by Administrator on 2018/4/8 0008.
*/
public class combinationSum2 {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> result=new ArrayList<>();
Arrays.sort(candidates);
if(candidates[0]>target) return result;
int length=candidates.length;
int sum=0;
for(int i=0;i<length;i++){
sum=sum+candidates[i];
}
if(sum<target)
return result;
List<Integer> list=new ArrayList<>();
backtracking(result,list,candidates,target,0);
List<List<Integer>> newList2 = new ArrayList();
return result;
}
public static void backtracking(List<List<Integer>> result,List<Integer> list,int[] candidateds,int target,int start){
if(0==target){
result.add(new ArrayList<>(list));
return;
}
else if(0>target)
return;
else {
int pre = -1; //去重复
for(int i=start;i<candidateds.length;i++) {
if(candidateds[i] == pre)
continue;
pre = candidateds[i];
list.add(candidateds[i]);
backtracking(result,list,candidateds,target-candidateds[i],i);
list.remove(list.size()-1);
}
}
}
public static void main(String[] args) {
int[] array=new int[]{1, 2, 3, 4, 5, 6, 7,8,9};
combinationSum2 com=new combinationSum2();
List<List<Integer>> result=new ArrayList<>();
result=com.combinationSum2(array,10);
System.out.println(result);
}
}