zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Matrix Power Series
    Recursive sequence HDU5950
    P2151 [SDOI2009]HH去散步
    P4273 [NOI2004] 降雨量
    P1034 [NOIP2002 提高组] 矩形覆盖
    P1027 [NOIP2001 提高组] Car 的旅行路线
    Win10使用Dism++离线安装.Net3.5
    WPF之模板
    WPF之资源
    WPF之命令
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4403421.html
Copyright © 2011-2022 走看看