Leetcode 18. 4Sum

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]
]
 
 

本题和3Sum差不多,但是更复杂一点的是,需要用两个for loop来循环 i, j, k, l 的前两个。然后 k,l 的处理方式和3Sum中一样。

 1 class Solution(object):
 2     def fourSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[List[int]]
 7         """
 8         
 9         nums.sort()
10         n = len(nums)
11         ans = []
12         for i in range(n):
13             if i>0 and nums[i] == nums[i-1]: continue
14             for j in range(i+1, n):
15                 if j>i+1 and nums[j] == nums[j-1]: continue
16                 k, l = j+1, n-1
17                 while k < l:
18                     if nums[i] + nums[j] + nums[k] + nums[l] < target:
19                         k += 1
20                     elif nums[i] + nums[j] + nums[k] + nums[l] > target:
21                         l -= 1
22                     else:
23                         ans.append([nums[i], nums[j], nums[k], nums[l]])
24                         while k < l and nums[k] == nums[k+1]: k += 1
25                         while k < l and nums[l] == nums[l-1]: l -= 1
26                         k += 1; l -= 1
27         return ans

 

posted @ 2017-01-06 10:30  lettuan  阅读(120)  评论(0编辑  收藏  举报