建议先看3Sum,然后更容易理解4Sum.
3Sum链接http://blog.youkuaiyun.com/lis_12/article/details/53207418
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
举例:
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
'''
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
length = len(nums)
if length < 4:
return []
nums.sort() #先排序
result = []
for index1,val1 in enumerate(nums[:-3]):
if index1 > 0 and nums[index1] == nums[index1 - 1]:
continue
for index2,val2 in enumerate(nums[index1 + 1:][:-2]):
if index2 > 0 and nums[index1 + index2 + 1] == nums[index1 + index2]:
continue
target2 = target - val1- val2
first = index1 + index2 + 2
second = length - 1
while first < second:
if nums[first] + nums[second] == target2:
result.append([val1,val2,nums[first],nums[second]])
while first < second and nums[first] == nums[first + 1]: #两个条件位置不能颠倒,不然可能会越界
first += 1
while first < second and nums[second] == nums[second - 1]:
second -= 1
first += 1
second -= 1
elif nums[first] + nums[second] < target2:
first += 1
else:
second -= 1
return result
if __name__ == "__main__":
s = Solution()
print s.fourSum([0,0,0,0],0)
8999

被折叠的 条评论
为什么被折叠?



