Skip to content

Commit b9c5340

Browse files
authored
Create 4Sum.py
1 parent b312d2a commit b9c5340

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

medium/4Sum.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#18. 4Sum
2+
class Solution:
3+
def fourSum(self, nums: List[int], target: int):
4+
ans = []
5+
6+
def nSum(l: int, r: int, target: int, n: int, path: List[int], ans: List[List[int]]) -> None:
7+
if r - l + 1 < n or n < 2 or target < nums[l] * n or target > nums[r] * n:
8+
return
9+
if n == 2:
10+
while l < r:
11+
summ = nums[l] + nums[r]
12+
if summ == target:
13+
ans.append(path + [nums[l], nums[r]])
14+
l += 1
15+
while nums[l] == nums[l - 1] and l < r:
16+
l += 1
17+
elif summ < target:
18+
l += 1
19+
else:
20+
r -= 1
21+
return
22+
23+
for i in range(l, r + 1):
24+
if i > l and nums[i] == nums[i - 1]:
25+
continue
26+
27+
nSum(i + 1, r, target - nums[i], n - 1, path + [nums[i]], ans)
28+
29+
nums.sort()
30+
nSum(0, len(nums) - 1, target, 4, [], ans)
31+
return ans

0 commit comments

Comments
 (0)