File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ fun fourSum (nums : IntArray , target : Int ): List <List <Int >> {
3
+ nums.sort()
4
+ val res = ArrayList <ArrayList <Int >>()
5
+ val temp = ArrayList <Int >()
6
+
7
+ fun kSum (k : Int , start : Int , targetSum : Long ) {
8
+ if (k != 2 ) {
9
+ for (i in start.. (nums.size - k)) {
10
+ if (i > start && nums[i - 1 ] == nums[i])
11
+ continue
12
+
13
+ temp.add(0 , nums[i])
14
+ kSum(k - 1 , i + 1 , targetSum - nums[i])
15
+ temp.removeAt(0 )
16
+ }
17
+
18
+ return
19
+ }
20
+
21
+ var left = start
22
+ var right = nums.lastIndex
23
+ while (left < right) {
24
+ val sum = nums[left].toLong() + nums[right].toLong()
25
+ if (sum < targetSum) {
26
+ left++
27
+ } else if (sum > targetSum) {
28
+ right--
29
+ } else {
30
+ temp.add(0 , nums[left])
31
+ temp.add(0 , nums[right])
32
+ res.add(ArrayList (temp))
33
+ temp.removeAt(0 )
34
+ temp.removeAt(0 )
35
+
36
+ left++
37
+ while (left < right && nums[left - 1 ] == nums[left])
38
+ left++
39
+ }
40
+ }
41
+ }
42
+
43
+ kSum(4 , 0 , target.toLong())
44
+ return res
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments