package main
import (
"fmt"
"sort"
)
/*
给定一个包含 n 个整数的数组 nums 和一个目标值 target,
判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?
找出所有满足条件且不重复的四元组。
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
*/
// N 数之和的本质是,在有序数组内,寻找 N 个数的和恰好是 S
// 解决办法还是 3sum 3sum_closest 的双指针法,不过需要外部 N-2 层循环,内部双指针循环即可
// 注意双指针在遍历时外部所有循环要去重,指针移动时也要去重
func main() {
fmt.Println(fourSum([]int{1, 0, -1, 0, -2, 2}, 0)) // [[-2 -1 1 2] [-2 0 0 2] [-1 0 0 1]]
}
func fourSum(nums []int, target int) [][]int {
sort.Ints(nums)
n := len(nums)
var res [][]int
for i := 0; i < n-1; i++ {
if i > 0 && nums[i] == nums[i-1] {
continue
}
for j := i + 1; j < n; j++ {
if j > i+1 && nums[j] == nums[j-1] {
continue
}
head, tail := j+1, n-1
for head < tail {
sum := nums[i] + nums[j] + nums[head] + nums[tail]
switch true {
case sum < target:
head++
case sum > target:
tail--
default:
res = append(res, []int{nums[i], nums[j], nums[head], nums[tail]})
for head < tail && nums[head] == nums[head+1] {
head++
}
for head < tail && nums[tail] == nums[tail-1] {
tail--
}
head++
tail--
}
}
}
return res
}
}