forked from damaohongtu/JavaInterview
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathThreeSum_15.java
More file actions
63 lines (58 loc) · 1.76 KB
/
ThreeSum_15.java
File metadata and controls
63 lines (58 loc) · 1.76 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
package LeetCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Classname ThreeSum_15
* @Description TODO
* @Date 19-5-22 上午8:35
* @Created by mao<tianmao818@qq.com>
*/
public class ThreeSum_15 {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
if(nums.length==0){
return new ArrayList<>();
}
return kSum(nums,3,0,0);
}
public List<List<Integer>> kSum(int[] nums, int k, int target,int startIndex){
List<List<Integer>> res=new ArrayList<>();
if(nums.length-startIndex<k){
return res;
}
if(k==2){
int i=startIndex;
int j=nums.length;
while(i<j){
if(nums[i]+nums[j]==target){
List<Integer> temp=new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
while(i<j && nums[i]==nums[++i]);
while(i<j && nums[j]==nums[--j]);
res.add(temp);
}else if(nums[i]+nums[j]<target){
i++;
}else{
j--;
}
}
return res;
}else{
for(int i=startIndex;i<nums.length;i++){
if(i>startIndex && nums[i]==nums[i-1]){
continue;
}
List<List<Integer>>tempList=kSum(nums,k-1,target-nums[i],i+1);
for(List<Integer> temp:tempList){
//每一次的添加nums[i]
temp.add(0,nums[i]);
//添加到最终的结果中去
res.add(temp);
}
}
}
return res;
}
}