18.四数之和
跟三数之和完全一样的思路
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
indexs = {}
for i, num in enumerate(nums):
index = indexs.get(num, [])
index.append(i)
indexs[num] = index
res = set()
for i in range(len(nums)-3):
for j in range(i+1, len(nums)-2):
for l in range(j+1, len(nums)-1):
for k in indexs.get(target - nums[i] - nums[j] - nums[l], []):
if k not in [i,j, l]:
s = tuple(sorted([nums[i], nums[j], nums[l], target- nums[i] - nums[j] - nums[l]]))
res.add(s)
break
return list(res)