题目:
18. 四数之和
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:答案中不可以包含重复的四元组。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [], target = 0
输出:[]
提示:
0 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
解法:
暴力枚举四个数组中的数即可,由于题目要求去除重复的组合,则使用Arrays.sort(nums)对数组进行排序,然后才利用List的equals方法判断当前组合是否已经存在即可(排序的原因是,顺序不一样,也会使得equals方法返回false,而我们对数组排序之后能保证顺序一致,即值比较列表元素是否相等)
代码:
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums); //使用Arrays类对数组排序
List<List<Integer>> list=new ArrayList<>();
int n=nums.length;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
for(int x=j+1;x<n;x++){
for(int y=x+1;y<n;y++){
if(nums[i]+nums[j]+nums[x]+nums[y]==target){
List<Integer> l=new ArrayList<>();
l.add(nums[i]);
l.add(nums[j]);
l.add(nums[x]);
l.add(nums[y]);
if(!list.isEmpty()){
boolean flag=false;
for(List li:list){
if(li.equals(l)){
flag=true;
break;
}
}
if(!flag){
list.add(l);
}
}else{
list.add(l);
}
}
}
}
}
}
return list;
}
}