码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode------4Sum

时间:2015-04-08 21:11:27      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

标题: 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

 

leetcode------4Sum

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4403421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!