# 【LeetCode】923. 3Sum With Multiplicity 解题报告（Python）

900 篇文章 155 订阅
1033 篇文章 56 订阅

id： fuxuemingzhu

## 题目描述：

Given an integer array A, and an integer target, return the number of tuples i, j, k such that i < j < k and A[i] + A[j] + A[k] == target.

As the answer can be very large, return it modulo 10^9 + 7.

Example 1:

Input: A = [1,1,2,2,3,3,4,4,5,5], target = 8
Output: 20
Explanation:
Enumerating by the values (A[i], A[j], A[k]):
(1, 2, 5) occurs 8 times;
(1, 3, 4) occurs 8 times;
(2, 2, 4) occurs 2 times;
(2, 3, 3) occurs 2 times.


Example 2:

Input: A = [1,1,2,2,2,2], target = 5
Output: 12
Explanation:
A[i] = 1, A[j] = A[k] = 2 occurs 12 times:
We choose one 1 from [1,1] in 2 ways,
and two 2s from [2,2,2,2] in 6 ways.


Note:

• 3 <= A.length <= 3000
• 0 <= A[i] <= 100
• 0 <= target <= 300

## 解题方法

class Solution(object):
def threeSumMulti(self, A, target):
"""
:type A: List[int]
:type target: int
:rtype: int
"""
count = collections.Counter(A)
Aset = set(A)
Alist = list(Aset)
Alist.sort()
_lenA = len(Alist)
res = 0
for i in range(_lenA):
for j in range(i, _lenA):
c = target - Alist[i] - Alist[j]
if c >= Alist[j] and c in Aset:
if Alist[i] != Alist[j] != c:
res += count[Alist[i]] * count[Alist[j]] * count[c]
elif Alist[i] == Alist[j] and Alist[j] != c:
res += count[c] * self.caculate(count[Alist[i]], 2)
elif Alist[j] == c and Alist[i] != Alist[j]:
res += count[Alist[i]] * self.caculate(count[Alist[j]], 2)
elif Alist[i] == c and Alist[j] != c:
res += count[Alist[j]] * self.caculate(count[c], 2)
else:
res += self.caculate(count[Alist[i]], 3)
return res % (10 ** 9 + 7)

def caculate(self, x, i):
if i == 2:
return x * (x - 1) / 2
elif i == 3:
return x * (x - 1) * (x - 2) / 6


## 日期

2018 年 10 月 14 日 —— 周赛做出来3个题，开心

• 0
点赞
• 0
收藏
• 打赏
• 1
评论
12-06 603
10-05 183
08-12 806
06-28 6316
06-01 8450
03-03 3588
03-18 1138

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。