The key idea is to count the frequency of each number in the array, then iterate over all possible combinations of three numbers (x, y, z) such that x + y + z == target and x <= y <= z. For each valid triplet, calculate the number of ways to pick indices with the required values using combinatorics.
classSolution {
publicintthreeSumMulti(int[] arr, int target) {
long[] count =newlong[101];
for (int num : arr) count[num]++;
long ans = 0, mod = 1_000_000_007;
for (int x = 0; x <= 100; ++x) {
if (count[x]== 0) continue;
for (int y = x; y <= 100; ++y) {
if (count[y]== 0) continue;
int z = target - x - y;
if (z < y || z > 100 || count[z]== 0) continue;
if (x == y && y == z) {
ans += count[x]* (count[x]- 1) * (count[x]- 2) / 6;
} elseif (x == y && y != z) {
ans += count[x]* (count[x]- 1) / 2 * count[z];
} elseif (x < y && y == z) {
ans += count[x]* count[y]* (count[y]- 1) / 2;
} elseif (x < y && y < z) {
ans += count[x]* count[y]* count[z];
}
ans %= mod;
}
}
return (int) ans;
}
}
classSolution:
defthreeSumMulti(self, arr: List[int], target: int) -> int:
from collections import Counter
cnt = Counter(arr)
ans =0 mod =10**9+7for x in range(101):
if cnt[x] ==0:
continuefor y in range(x, 101):
if cnt[y] ==0:
continue z = target - x - y
if z < y or z >100or cnt[z] ==0:
continueif x == y == z:
ans += cnt[x] * (cnt[x] -1) * (cnt[x] -2) //6elif x == y != z:
ans += cnt[x] * (cnt[x] -1) //2* cnt[z]
elif x < y == z:
ans += cnt[x] * cnt[y] * (cnt[y] -1) //2elif x < y < z:
ans += cnt[x] * cnt[y] * cnt[z]
ans %= mod
return ans