[Leetcode] 15. 4Sum 四数之和

Related Topics:[Array][Hash Table][Two Pointers]
Similar Questions:[Two Sum][3Sum][4Sum II]

题目: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: 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]
]

LeetCode中关于数字之和还有其他几道,分别是[Two Sum 两数之和],[3Sum 三数之和],[3Sum Closest 最近三数之和],虽然难度在递增,但是整体的套路都是一样的,此题的O(n^3)解法的思路跟[3Sum 三数之和]基本没啥区别,就是多加了一层for循环,其他的都一样。

java解法:

class Solution {
    public List> fourSum(int[] nums, int target) {
        List> res=new LinkedList<>();
        Arrays.sort(nums);
        int i=0;
        while(i

你可能感兴趣的:([Leetcode] 15. 4Sum 四数之和)