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
最新推荐文章于 2025-08-08 12:00:00 发布
本文介绍了一种求解四数之和问题的算法实现,通过先排序再使用双指针技术来寻找四个数加起来等于目标值的所有组合。文章详细展示了如何避免重复解,并通过递归方式简化代码。
1万+

被折叠的 条评论
为什么被折叠?



