最近班班在工作场景中遇到了一个类似4Sum问题的需求问题,找我看看有没有什么好的解决方法,于是我就开始研究2Sum,3Sum,4Sum,NSum问题。

Question

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:

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

简单来说,给一个非有序的数字数组,然后给定一个target,计算有多少组不重复的集合,加起来的和为给定的target

Analysis

面对NSum问题,最简单最快捷的方法就是暴力枚举,但时间复杂度是O(N^3)。

基本思路就是先排序,然后外面套两层循环,target减去得出来的和,然后开始2Sum的方法,左右两边向中间移动。

每次左边和右边加起来的和等于target,这就是命中的一组。其中需要进行去重处理,其他的都是中规中矩的做法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution(object):
'''
题意:找到数列中所有和等于目标数的四元组,需去重
多枚举一个数后,参照3Sum的做法,O(N^3)
'''
def fourSum(self, nums, target):
nums.sort()
res = []
length = len(nums)
for i in range(0, length - 3):
if i and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, length - 2):
if j != i + 1 and nums[j] == nums[j - 1]:
continue
sum = target - nums[i] - nums[j]
left, right = j + 1, length - 1
while left < right:
if nums[left] + nums[right] == sum:
res.append([nums[i], nums[j], nums[left], nums[right]])
right -= 1
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] > sum:
right -= 1
else:
left += 1
return res

Reference

4Sum - LeetCode