leetcode------4Sum

标题: 4Sum
通过率: 21.4%
难度: 中等

Given an array S of n integers, are there elements abc, 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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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)

4sum相当于在3sum外加一层循环:直接看代码:

 1 class Solution:
 2     # @return a list of lists of length 4, [[val1,val2,val3,val4]]
 3     def fourSum(self, num, target):
 4         num.sort()
 5         ans = []
 6         for j in range(len(num)):
 7             for i in range(j+1, len(num)):
 8                 l, r = i + 1, len(num) - 1
 9                 while l < r:
10                     sum = num[j] + num[i] + num[l] + num[r] 
11                     if sum == target:
12                         tmp=[num[j],num[i], num[l], num[r]]
13                         if tmp not in ans:
14                             ans.append(tmp)
15                         l, r = l + 1, r - 1
16                     elif sum < target:
17                         l = l + 1
18                     else:
19                         r = r - 1   
20         return ans

 

posted @ 2015-04-08 19:25  pku_smile  阅读(136)  评论(0编辑  收藏  举报