forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKSum.java
More file actions
79 lines (63 loc) · 2.07 KB
/
KSum.java
File metadata and controls
79 lines (63 loc) · 2.07 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
package LeetCode;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class KSum {
public static List<List<Integer>> fourSum(int[]nums,int target){
List<List<Integer>> res=new LinkedList<>();
if (nums==null||nums.length==0){
return res;
}
Arrays.sort(nums);
res=kSum(4,nums,0,target);
return res;
}
public static List<List<Integer>> kSum(int k,int[] nums,int startIndex,int target){
//保存结果
List<List<Integer>> res=new LinkedList<>();
//不能够再进行增加了
if(k>nums.length-startIndex){
return res;
}
if(k==2){
int i=startIndex,j=nums.length-1;
while(i<j){
if(nums[i]+nums[j]==target){
List<Integer> temp=new LinkedList<>();
temp.add(nums[i]);
temp.add(nums[j]);
res.add(temp);
while(i<j&&nums[i]==nums[++i]);
while(i<j&&nums[j]==nums[--j]);
}else if(nums[i]+nums[j]<target){
i++;
}else {
j--;
}
}
return res;
}else{
//startIndex避免重复,去掉当前的数值
for(int i=startIndex;i<nums.length;i++){
//避免重复
if(i>startIndex && nums[i]==nums[i-1]){
continue;
}
List<List<Integer>>tempList=kSum(k-1,nums,i+1,target-nums[i]);
for(List<Integer> temp:tempList){
//每一次的添加nums[i]
temp.add(0,nums[i]);
//添加到最终的结果中去
res.add(temp);
}
}
return res;
}
}
public static void main(String[] args){
int[] nums={1,0,-1,0,-2,2};
int target=0;
List<List<Integer>> res=fourSum(nums,target);
System.out.println(res);
}
}