有了前面的基础这道题的思路也很清晰了,无非是把4Sum转换为3Sum解决。
这里实现Nsum完成对此类题的通用解法。
1 class Solution: 2 def twoSum(self, nums, target, index): 3 left, right = index, len(nums) - 1 4 result = [] 5 while left < right: 6 sum = nums[left] + nums[right] 7 if sum < target: 8 left += 1 9 elif sum > target: 10 right -= 1 11 else: 12 result.append([nums[left], nums[right]]) 13 while left < right and nums[left] == nums[left + 1]: 14 left += 1 15 while left < right and nums[right] == nums[right - 1]: 16 right -= 1 17 left += 1 18 right -= 1 19 return result 20 def nSum(self, nums, target, index, n): 21 result = [] 22 if n == 2: 23 return self.twoSum(nums, target, index) 24 else: 25 i = index 26 while i < len(nums) - n + 1 : 27 if i > index and nums[i] == nums[i-1]: 28 i += 1 29 continue 30 temp = self.nSum(nums, target - nums[i], i + 1, n - 1) 31 if len(temp) > 0 : 32 for t in temp: 33 t.append(nums[i]) 34 result.append(t) 35 i += 1 36 return result 37 def fourSum(self, nums, target): 38 nums.sort() 39 return self.nSum(nums, target, 0, 4)