-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFourSum_v0.py
More file actions
49 lines (40 loc) · 999 Bytes
/
FourSum_v0.py
File metadata and controls
49 lines (40 loc) · 999 Bytes
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
#!/usr/bin/env python
# encoding: utf-8
class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[][]}
def fourSum(self, nums, target):
nums.sort()
r = []
for i, n in enumerate(nums):
ts = threeSum(nums[i + 1:], target - n)
for t in ts:
tt = (n, ) + t
if tt not in r:
r.append(tt)
return r
def threeSum(nums, target):
r = []
for i, n in enumerate(nums):
ts = twoSum(nums[i + 1:], target - n)
for t in ts:
tt = (n, ) + t
if tt not in r:
r.append(tt)
return r
def twoSum(nums, target):
d = {}
r = []
for n in nums:
t = d.get(target - n)
if t:
r.append((target - n, n))
else:
d[n] = True
return r
if __name__ == '__main__':
a = [1, 0, -1, 0, -2, 2]
s = Solution()
r = s.fourSum(a, 0)
print r