leetcode 4Sum

本文介绍了一种求解四数之和问题的算法实现,通过先排序再使用双指针技术来寻找四个数加起来等于目标值的所有组合。文章详细展示了如何避免重复解,并通过递归方式简化代码。

题目链接

public class Solution {
    public   List<List<Integer>> fourSum(int[] nums,int target) {
        List<List<Integer>> result = new LinkedList<List<Integer>>();  
        Arrays.sort(nums);
        int last=Integer.MAX_VALUE;
        for(int i=0;i<nums.length;i++)
        {
            if(last==nums[i])
            {
                continue;
            }
            last=nums[i];

            for(int j=i+1;j<nums.length;j++)
            {
                int findSum=target-nums[i]-nums[j];

                List<List<Integer>> tempRow=fun(nums,findSum,j+1,nums.length-1);
                if(!tempRow.isEmpty())
                {
                    for (List<Integer> list : tempRow) {
                        List<Integer> aRow=new LinkedList<Integer>();
                        aRow.add(nums[i]);
                        aRow.add(nums[j]);
                        for (Integer integer : list) {
                            aRow.add(integer);
                        }
                        result.add(aRow);
                    }
                }
                while(j+1<nums.length&&nums[j+1]==nums[j])
                {
                    j++;
                }
            }


        }


        return result;
    }

    public List<List<Integer>> fun(int[] nums,int target,int start,int end)
    {

        List<List<Integer>> tempRow=new LinkedList<List<Integer>>();
        while(start<end)
        {

            if(nums[start]+nums[end]==target)
            {
                List<Integer> temp=new LinkedList<>();

                temp.add(nums[start]);
                temp.add(nums[end]);
                tempRow.add(temp);
                while(start<end&&nums[start]==nums[start+1])
                {
                    start++;
                }
                while(start<end&&nums[end-1]==nums[end])
                {
                    end--;
                }
                start++;
                end--;
            }
            else if(nums[start]+nums[end]<target)
            {
                start++;

            }
            else
            {
                end--;

            }
        }
        return tempRow;


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值