ksum问题可以夹逼做 复杂度减一维
同leetcode 15,16题一样
class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[][]}
def fourSum(self, nums, target):
nums.sort()
l = len(nums)
res = []
if l < 3:
return res
z = 0
while z < l -3:
i = z + 1
while i < l - 2:
j = i + 1
k = l - 1
while j < k:
##print i , j , k
if nums[i]+nums[k]+nums[j]+nums[z]>target:
k = k -1
elif nums[i]+nums[k]+nums[j]+nums[z]<target:
j = j + 1
else:
res.append([nums[z],nums[i],nums[j],nums[k]])
while j < k and nums[j] == nums[j+1]:
j = j + 1
while j < k and nums[k] == nums[k-1]:
k = k -1
j = j + 1
k = k - 1
while i < l - 2 and nums[i] == nums[i+1]:
i = i + 1
i = i + 1
while z < l - 3 and nums[z] == nums[z+1]:
z = z + 1
z = z + 1
return res
##print fourSum([1,1,-1,-1],0)