18.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package main
  2. import (
  3. "sort"
  4. )
  5. func threeSumForTarget(nums []int, target int) [][]int {
  6. if len(nums) < 3 {
  7. return [][]int{}
  8. }
  9. sort.Ints(nums)
  10. res := make([][]int, 0)
  11. for a := 0; a < len(nums)-2; a++ {
  12. if a > 0 && nums[a] == nums[a-1] {
  13. continue
  14. }
  15. // the same as twoSum: target -> -nums[a], nums -> nums[a+1:]
  16. // one or more or none solutions
  17. b, c := a+1, len(nums)-1
  18. for b < c {
  19. nb, nc := nums[b], nums[c]
  20. sum := nums[a] + nb + nc
  21. if sum < target {
  22. b++
  23. } else if sum > target {
  24. c--
  25. } else {
  26. res = append(res, []int{nums[a], nb, nc})
  27. for ; b < c && nums[b] == nb; b++ {
  28. }
  29. for ; b < c && nums[c] == nc; c-- {
  30. }
  31. }
  32. }
  33. }
  34. return res
  35. }
  36. func fourSum(nums []int, target int) [][]int {
  37. sort.Ints(nums)
  38. res := make([][]int, 0)
  39. for i := 0; i < len(nums)-3; i++ {
  40. if i > 0 && nums[i] == nums[i-1] {
  41. continue
  42. }
  43. tmp := threeSumForTarget(nums[i+1:], target-nums[i])
  44. for _, v := range tmp {
  45. res = append(res, append([]int{nums[i]}, v...))
  46. }
  47. }
  48. return res
  49. }
  50. /* func main() {
  51. a1 := []int{1, 0, -1, 0, -2, 2}
  52. fmt.Println(fourSum(a1, 0))
  53. } */