https://leetcode.com/problems/4sum/
经典,就算看过多少遍,还是那么难写出来。

个人解答

  1. class Solution:
  2. def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
  3. nums.sort()
  4. def kSum(a, k, t):
  5. res = []
  6. if k == 2:
  7. # 2-sum
  8. l, r = 0, len(a) - 1
  9. while l < r:
  10. s = a[l] + a[r]
  11. if s == t:
  12. res.append([a[l], a[r]])
  13. l += 1
  14. r -= 1
  15. while l < len(a) and a[l] == a[l - 1]:
  16. l += 1
  17. while r >= 0 and a[r] == a[r + 1]:
  18. r -= 1
  19. elif s < t:
  20. l += 1
  21. while l < len(a) and a[l] == a[l - 1]:
  22. l += 1
  23. else:
  24. r -= 1
  25. while r >= 0 and a[r] == a[r + 1]:
  26. r -= 1
  27. else:
  28. for i in range(0, len(a) - k + 1):
  29. if i > 0 and a[i] == a[i - 1]:
  30. continue
  31. ret = kSum(a[i + 1:], k - 1, t - a[i])
  32. res += [[a[i]] + l for l in ret]
  33. return res
  34. return kSum(nums, 4, target)

题目分析

对于K-sum,归约成K-1 sum
到最后,变成2-sum

需要考虑重复的情况