LeetCode-18.4Sum

来源:互联网 发布:增加人脉的软件 编辑:程序博客网 时间:2024/04/30 01:19

https://leetcode.com/problems/4sum/

Given an array S of n integers, are there elements abc, 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]]

方法1

利用题15.3Sum 的函数稍作修改,然后在外层再嵌套一层循环

public class Solution {    public IList<IList<int>> FourSum(int[] nums, int target)     {        IList<IList<int>> res = new List<IList<int>>();        int n = nums.Length;        if (n < 4)            return res;        Array.Sort(nums);        for (int i = 0; i < n-3; i++)        {            var res3 = ThreeSum(i + 1, nums, target - nums[i]);            if (res3.Count > 0)            {                foreach (var list in res3)                {                    list.Insert(0, nums[i]);                    res.Add(list);                }            }            while (i < n - 3 && nums[i] == nums[i + 1])                i++;        }        return res;    }    public IList<IList<int>> ThreeSum(int start,int[] nums,int target)    {        IList<IList<int>> res = new List<IList<int>>();        int n = nums.Length;        int target2,l,r;        for (int i = start; i < n-2; i++)        {            target2 = target - nums[i];            l = i + 1;            r = n - 1;            while (l<r)            {                if (nums[l] + nums[r] > target2)                    r--;                else if (nums[l] + nums[r] < target2)                    l++;                else                {                    res.Add(new List<int>() { nums[i], nums[l] ,nums[r] });                    while (i < n - 2 && nums[i] == nums[i + 1])                        i++;                    while (l < n - 1 && nums[l] == nums[++l]);                    while (r > i + 1 && nums[r] == nums[--r]);                }            }        }        return res;    }}

方法2

方法略繁琐,可以扩展到k-sum。有兴趣可以参考 http://blog.csdn.net/linhuanmars/article/details/24826871 

0 0
原创粉丝点击