不用哈希法,排序后用双指针,比三数之和多一层:
func fourSum(nums []int, target int) [][]int {
res := [][]int{}
sort.Ints(nums)
for i := 0; i < len(nums)-3; i++ {
n1 := nums[i]
// 去重
if i > 0 && n1 == nums[i-1] {
continue
}
for j := i + 1; j < len(nums)-2; j++ {
n2 := nums[j]
// 去重
if j > i + 1 && n2 == nums[j-1] {
continue
}
// 双指针
l, r := j + 1, len(nums)-1
for l < r {
n3, n4 := nums[l], nums[r]
sum := n1 + n2 + n3 + n4
if sum < target {
l++
} else if sum > target {
r--
} else {
res = append(res, []int{n1, n2, n3, n4})
// 去重
for l < r && n3 == nums[l+1] { l++ }
for l < r && n4 == nums[r-1] { r-- }
l++
r--
}
}
}
}
return res
}