Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:

Given array nums = [, , -, , -, ], and target = .

A solution set is:
[
[-, , , ],
[-, -, , ],
[-, , , ]
]

思路


  在看到这道题之后,我第一反应是使用之前求三数之和那样求四数之和,结果也是可行,但是运行结果显示的时间复杂度太高。这里我先将我自己的解决思路写下来

  时间复杂为O(n3),空间复杂为O(1)。

解决代码


 class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
if len(nums) < : # 异常情况,小于四个直接返回
return []
if len(nums) == and sum(nums) == target:
return [nums]
nums.sort() # 先进行排序
res = []
for i in range(len(nums)-): # 第一个下标
if i > and nums[i] == nums[i-]: # 遇到重复的直接跳过
continue
for j in range(i+, len(nums)-): # 第二个下标
if j > i+ and nums[j] == nums[j-]: # 遇到重复直接跳过
continue
start, end = j+, len(nums)-1 # 另外两个下标,指向头和尾部
while start < end:
tem = nums[i] + nums[j] + nums[start] + nums[end]
if tem - target > : # 进行判断,选择相应的移位
end -=
elif tem - target < :
start +=
else: # 找到符合条件的四个数字。
res.append([nums[i], nums[j], nums[start], nums[end]]) # 将其添加进结果集中
while start < end and nums[start] == nums[start+]: # 相同元素直接跳过。
start +=
while start < end and nums[end] == nums[end-]: # 相同元素直接跳过
end -=
start +=
end -=
return res
改进

  上面的算法,在实现之后效率太低,以至于运行结果之超过了百分之10的用户。但是由于自己也想不出什么好的办法,因此取讨论区看了别人的写法,不得不说确实很厉害。下面写上别人给出了一个解决方法,这个方法可以解决N数和的问题。

解决思路以及代码


  这个问题他的解决思路主要是通过分解,将N数和的问题转化为两数和的问题(递归),并且通过传递变量来记录满足结果的条件。

 def fourSum(self, nums, target):
nums.sort()
results = []
self.findNsum(nums, target, , [], results) #因为本题是4数之和的问题,所以传入的参数是4,并且将保存满足条件的数字的变量进行传递
return results def findNsum(self, nums, target, N, result, results):
if len(nums) < N or N < : return # 数组的长度小于N(N数之和)时或者小于2时,直接返回条件。
# solve -sum
if N == : # 当N == 2 时,进行判断, 里面的步骤和三数问题中的步骤一样。
l,r = ,len(nums)-
while l < r:
if nums[l] + nums[r] == target:
results.append(result + [nums[l], nums[r]])
l +=
r -=
while l < r and nums[l] == nums[l - ]:
l +=
while r > l and nums[r] == nums[r + ]:
r -=
elif nums[l] + nums[r] < target:
l +=
else:
r -=
else: # N大于2时进行递归,分解
for i in range(, len(nums)-N+): # careful about range # 第一个指针位置
if target < nums[i]*N or target > nums[-]*N: # 意外情况判定,因为数组是已经排好序的,当第一个元素(最小)乘
break          # 以N时,还比target大,那说明,后面的都不满足,直接返回。后面同理。
if i == or i > and nums[i-] != nums[i]: #recursively reduce N #从第一个看是遍历,并将相应额结果进行传递。
self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)
return

【LeetCode每天一题】4Sum(4数之和)的更多相关文章

  1. LeetCode每天一题之两数之和

    这个LeetCode刷题系列的博客权当是为自己记一下笔记吧.博客系列会从LeetCode的第一题开始刷,同时会从零开始学习[因为我就是零/(ㄒoㄒ)/~~].同时,如果有写错的地方,希望大佬们在评论区 ...

  2. leetcode第15题:三数之和

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

  3. Leetcode第1题:两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数.你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元素.示例:给定 nums ...

  4. 【LeetCode】18. 4Sum 四数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:four sum, 4sum, 四数之和,题解,leet ...

  5. LeetCode(1): 两数之和

    本内容为LeetCode第一道题目:两数之和 # -*- coding: utf-8 -*- """ Created on Sun Mar 10 19:57:18 201 ...

  6. LeetCode:最接近的三数之和【16】

    LeetCode:最接近的三数之和[16] 题目描述 给定一个包括 n 个整数的数组 nums 和 一个目标值 target.找出 nums 中的三个整数,使得它们的和与 target 最接近.返回这 ...

  7. Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted)

    Leetcode之二分法专题-167. 两数之和 II - 输入有序数组(Two Sum II - Input array is sorted) 给定一个已按照升序排列 的有序数组,找到两个数使得它们 ...

  8. LeetCode刷题 - (01)两数之和

    题目描述 给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中同样的元 ...

  9. 【LeetCode刷题】——两数之和.1

    ---恢复内容开始--- 一直想在leetcode上面刷题,但是java刚刚摸了一下门,所以迟迟没有动手,今天做了第一道题,感觉自己实在菜的不行,但是还是学到了很多东西, 就记录一下遇到的问题. 首先 ...

  10. C#LeetCode刷题之#15-三数之和(3Sum)

    目录 问题 示例 分析 问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3618 访问. 给定一个包含 n 个整数的 ...

随机推荐

  1. cordova 企业应用打包Archive的时候报 "#import <Cordova file not found"

    可能原因是Cordova的路径问题: For xcode7 add "$(OBJROOT)/UninstalledProducts/$(PLATFORM_NAME)/include" ...

  2. thinkphp5---如何使用公共类

    在进行项目开发的时候,有很多的类是前后台以及其他模块都会使用的,例如验证码,上传类,密码加密的类等以及一些其他的第三方类库,如何在项目中提取这些公共的类呢? 具体方法: 例如:我在这里定义上传的类,里 ...

  3. 7.9CSS总结

    2018-7-9 18:01:18 1.类选择器是 用  .      .xxx{}  (ps,公司常用的是类选择  ) 2.id选择器是用  #   #xx{}  (id选择器并不常用) 3.css ...

  4. day_5.21 py 高级编程

    1.禁止模块之间的循环调用 2.浅拷贝    只拷贝引用!!\ 3. 深拷贝  只要里面有引用就继续拷贝 4.copy,copy() 5. '''2018-5-21 11:39:52就业班 py高级 ...

  5. MyBatis limit分页设置

    错误的写法: <select id="queryMyApplicationRecord" parameterType="MyApplicationRequest&q ...

  6. 壁虎书4 Training Models

    Linear Regression The Normal Equation Computational Complexity 线性回归模型与MSE. the normal equation: a cl ...

  7. Kindle2018 一周使用报告

    使用2018年年末刚刚发布的KPW有一周时间了,可以借这个机会来对这部设备做一个使用报告了. 那咱们就参考如下描述吧: 1.轻薄便携:6英寸的屏幕,11.6厘米*16.7厘米的机身尺寸,加上仅有8.2 ...

  8. MS14-064 漏洞测试入侵——20145301

    MS14-064 漏洞测试入侵 Microsoft Windows OLE远程代码执行漏洞,OLE(对象链接与嵌入)是一种允许应用程序共享数据和功能的技术 执行摘要 此安全更新可解决 Microsof ...

  9. Ubuntu 安装 .bundle 文件

    ubuntu安装VMware-Workstation-Full-15.0.2-10952284.x86_64.bundle 一.*.bundle 文件比较特殊,只有在给它了执行权限后才能执行安装操作. ...

  10. HDU 4699 - Editor - [对顶栈]

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4699 Problem Description Sample Input8I 2I -1I 1Q 3LD ...