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;


    }
}

你可能感兴趣的:(leetcode 4Sum)