-
Notifications
You must be signed in to change notification settings - Fork 0
/
4sum.py
35 lines (33 loc) · 1.22 KB
/
4sum.py
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
class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
def findNsum(nums, target, N, cur):
if len(nums) < N or N < 2 or nums[0] * N > target or nums[-1] * N < target: # pruning
return
if N == 2:
l, r = 0, len(nums) - 1
while l < r:
s = nums[l] + nums[r]
if s == target:
res.append(cur + [nums[l], nums[r]])
while l < r and nums[l] == nums[l - 1]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif s < target:
l += 1
else:
r -= 1
else:
for i in range(len(nums) - N + 1):
if i == 0 or nums[i - 1] != nums[i]:
findNsum(nums[i + 1 :], target - nums[i], N - 1, cur + [nums[i]])
res = []
findNsum(sorted(nums), target, 4, [])
return res