# Leetcode 18:四数之和（最详细解决方案！！！）

给定数组 nums = [1, 0, -1, 0, -2, 2]，和 target = 0。

[
[-1,  0, 0, 1],
[-2, -1, 1, 2],
[-2,  0, 0, 2]
]


class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
for i, a in enumerate(nums):
for j, b in enumerate(nums[i + 1:]):
for k, c in enumerate(nums[j + i + 2:]):
for _, d in enumerate(nums[i + j + k + 3:]):
if a + b + c + d == 0:
result.append([a, b, c, d])
return result


class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
nums_len = len(nums)
nums.sort()
for i in range(nums_len - 3):
if i > 0 and nums[i - 1] == nums[i]:
continue

for j in range(i+1, nums_len - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
l, r = j + 1, nums_len - 1
while l < r:
if nums[i] + nums[j] + nums[l] + nums[r] == target:
result.append([nums[i], nums[j], 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 nums[i] + nums[j] + nums[l] + nums[r] < target:
l += 1
else:
r -= 1
return result


class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = list()
nums_len = len(nums)
nums.sort()

for i in range(nums_len - 3):
if (nums[i] << 2) > target: # prune
break
if i > 0 and nums[i - 1] == nums[i]:
continue

for j in range(nums_len-1, i+2, -1):
if (nums[j] << 2) < target: # prune
break
if j < nums_len-1 and nums[j] == nums[j + 1] :
continue

l, r = i+1, j-1
while l < r:
if nums[i] + nums[j] + nums[l] + nums[r] == target:
result.append([nums[i], nums[j], 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 nums[i] + nums[j] + nums[l] + nums[r] < target:
l += 1
else:
r -= 1
return result


class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
result = list()
nums_len = len(nums)
if nums_len < 4:
return result

if nums[0] * 4 > target or nums[nums_len - 1] * 4 < target:
return result

nums_map = {}
for i in range(nums_len-1, 0, -1):
if i < nums_len - 1 and nums[i] == nums[i + 1]:
continue
for j in range(i-1, -1, -1):
if j < i-1 and nums[j] == nums[j + 1]:
continue
if nums[i] + nums[j] not in nums_map:
nums_map[nums[i] + nums[j]] = [[j, i]]
else:
nums_map[nums[i] + nums[j]].append([j, i])

for i in range(nums_len - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i+1, nums_len - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue

dif = target - nums[i] - nums[j]
if dif not in nums_map:
continue
else:
for num in nums_map[dif]:
if num[0] > j:
result.append([nums[i], nums[j], nums[num[0]], nums[num[1]]])
return result