-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNsum.java
More file actions
78 lines (68 loc) · 1.94 KB
/
Copy pathNsum.java
File metadata and controls
78 lines (68 loc) · 1.94 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
package AlgorithmTest;
import java.util.*;
/*
*Nsum 问题
*
* 2sum问题
* 思路:头尾双向遍历
* 3sum问题
*
* 4sum问题
*
*
* */
public class Nsum {
public static void main(String[] args) {
int Arr[]={-1,0,1,2,-1,-4};
//1.2,2,3,3,4,5
// TSum(Arr,5,0,Arr.length-1);
ThSum(Arr,0);
}
//2 Sum
public static List<List<Integer>> TSum(int [] Arr,int target,int start,int end) {
Arrays.sort(Arr); //排序
int head=start;
int tail=end;
List<List<Integer>> result=new ArrayList<>();
while(head<tail){
if (Arr[head]+Arr[tail]>target){
tail--;
}else if (Arr[head]+Arr[tail]<target){
head++;
}else{
if (head>1&&Arr[head-1]==Arr[head]&&Arr[tail+1]==Arr[tail]){
head+=2;
tail+=2;
continue;
}
List<Integer> tempList= new ArrayList<>();
tempList.add(Arr[head]);
tempList.add(Arr[tail]);
result.add(tempList);
head++;
tail--;
}
}
// System.out.println(result);
return result;
}
public static List<List<Integer>> ThSum(int [] Arr,int target) {
Arrays.sort(Arr);
List<List<Integer>> result=new ArrayList<>();
for (int i=0;i<Arr.length;i++){
List<List<Integer>> TList=TSum(Arr,target-Arr[i],i+1,Arr.length-1);
int size=TList.size();
if (size>0){
for (int j=0;j<size;j++){
List<Integer> tempList= new ArrayList<>();
tempList.addAll(TList.get(j));
tempList.add(Arr[i]);
result.add(tempList);
}
}
}
return result;
}
public static void FSum(int [] Arr,int target) {
}
}