- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSolution698.java
More file actions
Latest commit
executable file
·62 lines (55 loc) · 1.84 KB
/
Copy pathSolution698.java
File metadata and controls
executable file
·62 lines (55 loc) · 1.84 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
importjava.util.*;
publicclassSolution698 {
publicbooleancanPartitionKSubsets(int[] nums, intk) {
intsum=0;
booleanlabel = false;
intlen = nums.length;
//当前元素是否被使用过
boolean[] mark = newboolean[len];
//判断是否存在可能
for (inti = 0; i <len ; i++) {
sum = sum +nums[i];
}
// 每个组内的目标和的值
inttarget = sum/k;
inttag = sum%k;
if (tag!=0){
returnfalse;
}
//是否存在大于目标值得情况
LinkedList<Integer> numsList = newLinkedList<Integer>();
for(inti:nums){
if (i>target){
label = true;
break;
}
numsList.add(i);
}
if (label){
returnfalse;
}else {
returnhelp(numsList,mark,k, 0,target,0);
}
}
booleanhelp(LinkedList<Integer> numsList,boolean[] mark,intk,intstart,inttarget,intcurSum){
//配对完成
if (k==1) returntrue;
//进行下一组配对,重置初始位置,重置初始和
if (curSum==target) returnhelp(numsList,mark,k-1,0,target,0);
//for循环为了遍历所有节点,找到所有子集
for (inti = start;i<numsList.size();i++){
if (mark[i]) continue;
//标记已经使用过的元素
mark[i]=true;
//递归寻找满足curSum==target条件的元素组合
if (help(numsList,mark,k,i+1,target,numsList.get(i)+curSum)) returntrue;
mark[i] = false;
}
returnfalse;
}
publicstaticvoidmain(String[] args) {
Solution698s = newSolution698();
int[] a = {2,2,10,5,2,7,2,2,13};
System.out.println(s.canPartitionKSubsets(a,3));
}
}