首页 > 代码库 > [leetcode]18. 4Sum

[leetcode]18. 4Sum

求一个数组中任意四个数的和为target的所有组合

思路:求n个数的和为target,转变为求n-1个书的和为target-num

 1 class Solution(object):
 2     def fourSum(self, nums, target):
 3         nums.sort()
 4         ress = []
 5         self.find(nums,target,4,[],ress)
 6         return ress
 7     
 8     def find(self,nums,target,n,res,ress):
 9         if n == 2:
10             l,r = 0,len(nums)-1
11             while l<r:
12                 if nums[l]+nums[r]==target:
13                     ress.append(res+[nums[l],nums[r]])
14                     l += 1
15                     r -= 1
16                     while l<r and nums[l] == nums[l-1]:
17                         l += 1
18                     while l<r and nums[r] == nums[r+1]:
19                         r -= 1
20                 elif nums[l]+nums[r] <target:
21                     l += 1
22                 else:
23                     r -= 1
24         else:
25             for i in range(len(nums)-n+1):
26                 if target < nums[i]*n or target > nums[-1]*n:
27                     break
28                 if not i or nums[i]!=nums[i-1]:
29                     self.find(nums[i+1:],target-nums[i],n-1,res+[nums[i]],ress)
30         return 
31             
32             
33             
34             

 

[leetcode]18. 4Sum