923. 3Sum With Multiplicity
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
方法0: dfs, TLE
思路:
class Solution {
public:
int threeSumMulti(vector<int>& A, int target) {
int res = 0;
multiHelper(A, target, 0, 0, res, 3);
return res;
}
void multiHelper(vector<int> & A, int target, int start, int curSum, int & res, int count) {
if (curSum < 0) return;
if (count == 0) {
if (curSum == target) {
res++;
res %= ((int)pow(10, 9) + 7);
}
return;
}
for (int i = start; i < A.size(); i++) {
multiHelper(A, target, i + 1, curSum + A[i], res, count - 1);
}
return;
}
};
方法1: two pointers
思路:
class Solution {
public:
int threeSumMulti(vector<int>& A, int target) {
int n = A.size();
long long int cnt[101];
memset(cnt, 0, sizeof(cnt));
for (int i: A) cnt[i]++;
long long int res = 0, MOD = 1e9 + 7;
// different: i <= j <= k;
for (int i = 0; i <= min(100, target); i++) {
if (!cnt[i]) continue;
for (int j = i; j <= 100 && i + j <= target && j <= target - i - j; j++) {
int k = target - i - j;
if (k > 100) continue;
if (!cnt[i] || !cnt[j]) continue;
if (i != j && j != k) {
res = (res + cnt[i] * cnt[j] * cnt[k]) % MOD;
}
else if (i != j && j == k && cnt[j] >= 2) {
res = (res + cnt[i] * cnt[j] * (cnt[j] - 1) / 2) % MOD;
}
else if (i == j && j != k && cnt[i] >= 2) {
res = (res + cnt[i] * (cnt[i] - 1) / 2 * cnt[k]) % MOD;
}
else if (i == j && j == k && cnt[i] >= 3) {
res = (res + cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / 6) % MOD;
}
}
}
return res;
}
};