1 """ 2 Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero. 3 To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1. 4 Example: 5 Input: 6 A = [ 1, 2] 7 B = [-2,-1] 8 C = [-1, 2] 9 D = [ 0, 2] 10 Output: 11 2 12 Explanation: 13 The two tuples are: 14 1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0 15 2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0 16 """ 17 """ 18 I feel my IQ is screwed like a shit by this answer 19 将A+B的和记录在dict中。key为sum,value为sum出现的次数 20 依次求-(C+D),判断是否在dict中。如果在 21 res 加上value 22 """ 23 class Solution: 24 def fourSumCount(self, A, B, C, D): 25 import collections 26 res = 0 27 dic = {} 28 for a in A: 29 for b in B: 30 if (a+b) in dic: 31 dic[a+b] += 1 32 else: 33 dic[a+b] = 1 34 for c in C: 35 for d in D: 36 if -(c+d) in dic: 37 res += dic[-c-d] 38 return res 39 if __name__ == '__main__': 40 ans = Solution() 41 A = [1, 2] 42 B = [-2, -1] 43 C = [-1, 2] 44 D = [0, 2] 45 print(ans.fourSumCount(A, B, C, D))