-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18 4sum (N sum problem)
62 lines (59 loc) · 2.37 KB
/
18 4sum (N sum problem)
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
def twoSum(self,nums,target):
solution = []
second,third = 0,len(nums)-1
while second < third:
if nums[second] + nums[third] > target:
third -= 1
elif nums[second] + nums[third] < target:
second += 1
else:
solution.append([nums[second],nums[third]])
while second < third and nums[second] == nums[second+1]:
second += 1
while second < third and nums[third] == nums[third-1]:
third -= 1
second += 1
third -= 1
return solution
def fourSum(self, nums, target):
final_solution = []
nums.sort()
for first in range(len(nums)-3):
if first-1 >=0 and nums[first] == nums[first-1]:
continue
for second in range(first+1,len(nums)-2):
if second > first+1 and nums[second] == nums[second-1]:
continue
solution = self.twoSum(nums[second+1:],target-nums[first]-nums[second])
for x in solution:
final_solution.append([nums[first],nums[second]]+x)
return final_solution
solve N-sum problem:
def NSum(self,nums,target,N,result,solution):
if N <= 1 or N > len(nums) or len(nums) == 0 or target < nums[0] * N or target > nums[len(nums)-1] * N:
return
elif N == 2:
i,j = 0,len(nums)-1
while i < j:
if nums[i] + nums[j] > target:
j -= 1
elif nums[i] + nums[j] < target:
i += 1
else:
solution.append(result + [nums[i],nums[j]])
while i < j and nums[i] == nums[i+1]:
i += 1
while i < j and nums[j] == nums[j-1]:
j -= 1
i += 1
j -= 1
elif N > 2:
for first in range(len(nums)-N+1):
if first-1 >= 0 and nums[first] == nums[first-1]:
continue
self.NSum(nums[first+1:],target-nums[first],N-1,[nums[first]] + result,solution)
def fourSum(self,nums,target):
solution = []
nums.sort()
self.NSum(nums,target,4,[],solution)
return solution