N数之和
import org.graalvm.compiler.nodes.KillingBeginNode;
import org.graalvm.compiler.nodes.calc.LeftShiftNode;
import java.sql.Array;
import java.util.ArrayList;
import java.util.Arrays;
/**
* <p>给你一个由 <code>n</code> 个整数组成的数组 <code>nums</code> ,和一个目标值 <code>target</code> 。请你找出并返回满足下述全部条件且<strong>不重复</strong>的四元组 <code>[nums[a], nums[b], nums[c], nums[d]]</code> (若两个四元组元素一一对应,则认为两个四元组重复):</p>
*
* <ul>
* <li><code>0 <= a, b, c, d < n</code></li>
* <li><code>a</code>、<code>b</code>、<code>c</code> 和 <code>d</code> <strong>互不相同</strong></li>
* <li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li>
* </ul>
*
* <p>你可以按 <strong>任意顺序</strong> 返回答案 。</p>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>nums = [1,0,-1,0,-2,2], target = 0
* <strong>输出:</strong>[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>nums = [2,2,2,2,2], target = 8
* <strong>输出:</strong>[[2,2,2,2]]
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>1 <= nums.length <= 200</code></li>
* <li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
* <li><code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code></li>
* </ul>
* <div><div>Related Topics</div><div><li>数组</li><li>双指针</li><li>排序</li></div></div><br><div><li>👍 1320</li><li>👎 0</li></div>
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Arrays.sort(nums);
return nSumTarget(nums,4,0,target);
}
public List<List<Integer>> nSumTarget(int[] nums, int n, int start, long target) {
List<List<Integer>> res = new ArrayList<>();
int sz = nums.length;
if (n < 2 || sz < n) return res;
if (n == 2) {
int left = start, right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
int low = nums[left];
int high = nums[right];
if (sum > target)
while (left < right && nums[right] == high) right--;
else if (sum < target)
while (left < right && nums[left] == low) left++;
else {
res.add(Arrays.asList(nums[left], nums[right]));
while (left < right && nums[right] == high) right--;
while (left < right && nums[left] == low) left++;
}
}
} else {
for (int i = start; i < nums.length; i++) {
int num = nums[i];
List<List<Integer>> twoSum = nSumTarget(nums, n - 1, i + 1, target - num);
for (int j = 0; j < twoSum.size(); j++) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.addAll(twoSum.get(j));
res.add(temp);
}
while (i < nums.length - 1 && num == nums[i + 1]) {
i++;
}
}
}
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)
不恋尘世浮华,不写红尘纷扰