/*
* @lc app=leetcode.cn id=18 lang=java
*
* [18] 四数之和
*/
// InetgerCharacterllengthremoveAtInetgerCharacter@lc code=start
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> re = new ArrayList<>();
// 先排序
Arrays.sort(nums);
// target : 目标值
// 4 : 处理4次
// nums : 采样数组
// 0 : 开始下标
// re : 结果变量
// new ArrayList<>(4) : 零时变量可以确定只存储4个元素
calFourSum(target, 4, nums, 0, re, new ArrayList<>(4));
return re;
}
private void calFourSum(int target, int times, int[] nums, int index, List<List<Integer>> re, List<Integer> sub){
if(times == 0){
// 当已经获取4个数检查是否满足和为target
if(target == 0)
re.add(new ArrayList<>(sub));
return;
}else if(times > nums.length - index){
// 当可获取个数少于times直接返回
return;
}
for(int i = index; i < nums.length;){
// 加入当前节点
sub.add(nums[i]);
calFourSum(target - nums[i], times - 1, nums, i + 1, re, sub);
// 移除当前节点
sub.remove(sub.size() - 1);
// 设置下一个i对应的值不同于当前i对应的值
if(i + 1 < nums.length && nums[i] == nums[i + 1]){
int ts = 2;
while(ts + i < nums.length && nums[ts + i] == nums[i]){
ts++;
}
i += ts;
}else{
i++;
}
}
return;
}
}
10-05
588