1.题目描述
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
.
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
Note:
The solution set must not contain duplicate quadruplets.
答案中不可以包含重复的四元组。
Example:
Given array nums = [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]
]
2.Solutions
If you have already read and implement the 3sum and 4sum by using the sorting approach: reduce them into 2sum at the end, you might already got the feeling that, all ksum problem can be divided into two problems:
- 2sum Problem
- Reduce K sum problem to K – 1 sum Problem
Therefore, the ideas is simple and straightforward. We could use recursive(递归) to solve this problem. Time complexity is O(N^(K-1)).
1 | public static List<List<Integer>> fourSum(int[] nums, int target) { |