4Sum
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.
(寻找数组中四个数的和为target的组合)
Example:

1. 四个指针
可以将这个题理解为与之前的 3Sum 类似,但是这里要有三重循环,其时间复杂度为 O(n3)。
1 | class Solution: |
2. 两次 2Sum + Dict
换一种思路,以空间换时间。我们可以将其转换为两次 2Sum 的过程。第一次 2Sum 遍历数组中所有的两个数的和,并将索引在 dict 中保存。第二次 2Sum 来判断数组中的和与 Dict 是否满足要求 Target。其时间复杂度为 O(n2)。
1 | class Solution: |
3. 递归 N-sum
这个是在提交之后看到的别人的解法,将 N-sum 的问题递归的向下传递为 N-1, N-2 等等的问题,最终归结为 2Sum 的问题。
1 | class Solution: |