class Solution {
public List<List<Integer>> nTargetSum(int[] nums, int nSum, int start, long target) {
int low = start;
int len = nums.length;
int high = len - 1;
List<List<Integer>> res = new ArrayList<>();
// 至少是 2Sum,且数组大小不应该小于 nums.length;
if(nSum < 2 || len < nSum) return res;
if (nSum == 2) {
while (low < high) {
int sum = nums[low] + nums[high];
int left = nums[low], right = nums[high];
if (sum > target) {
while (low < high && nums[high] == right) high--;
} else if (sum < target) {
while (low < high && nums[low] == left) low++;
} else {
List<Integer> temp = new ArrayList<>();
temp.add(nums[low]);
temp.add(nums[high]);
res.add(temp);
while (low < high && nums[high] == right) high--;
while (low < high && nums[low] == left) low++;
}
}
}
else if(nSum >2){
for (int i = start; i < len - nSum + 1; ++i) {
List<List<Integer>> nSub1_SumTarget = nTargetSum(nums,nSum-1, i + 1, target - nums[i]);
for (List<Integer> arr : nSub1_SumTarget) {
arr.add(nums[i]);
res.add(arr);
}
while (i < len - nSum + 1 && nums[i] == nums[i + 1]) i++;
}
}
return res;
}
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
return nTargetSum(nums,4,0,target);
}
}
由LeetCode18.四数和 推广到n数和问题
该代码段展示了一个Java类Solution,包含两个方法。fourSum()方法对输入数组进行排序后,调用nTargetSum()方法寻找数组中四个数之和为目标值的所有组合。nTargetSum()方法使用了递归,当目标和为2时,采用双指针法;否则,通过递归查找剩余数的三数之和。
摘要由CSDN通过智能技术生成