最重要的是main函数里面的for循环。
//以四数之和为例,nums为多个整数组成的数组,target为目标值
public static void main(String[] args) {
int[] nums = new int[]{1000000000,1000000000,1000000000,1000000000};
int target = -294967296;
Arrays.sort(nums);
List<List<Integer>> rs = new ArrayList<>();
rs = nSum(nums, 4, 0, target);
for (List<Integer> r : rs) {
int sum = 0;
for (Integer integer : r) {
sum += (double)integer;
}
if(sum != target) {
List<List<Integer>> error = new ArrayList<>();
}
}
}
public static List<List<Integer>> nSum(int[] nums, int n, int start, int target) {
int sz = nums.length;
List<List<Integer>> rs = new ArrayList<>();
if (n < 2 || nums.length < n) {
return rs;
}
if (n == 2) {
int left = start;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
int nums_left = nums[left];
int nums_right = nums[right];
if (sum < target) {
while (left < right && nums[left] == nums_left) {
left++;
}
}
else if (sum > target) {
while (left < right && nums[right] == nums_right) {
right--;
}
}
else if (sum == target) {
List<Integer> rs1 = new ArrayList<>();
Collections.addAll(rs1, nums[left], nums[right]);
rs.add(rs1);
while (left < right && nums[left] == nums[right]) {
left++;
}
while (left < right && nums[right] == nums_right) {
right--;
}
}
}
}
else {
for (int i = start; i < nums.length; i++) {
if ( i > start && nums[i] == nums[i - 1]) {
continue;
}
List<List<Integer>> rs2 = new ArrayList<>();
rs2 = nSum(nums, n-1, i+1,target - nums[i]);
for (List<Integer> arr : rs2) {
arr.add(nums[i]);
rs.add(arr);
}
}
}
return rs;
}
Leetcode15三数之和,Leetcode18四数之和已全通过。