题目:
思路:
https://www.jianshu.com/p/544cbb422300
代码:
int threeSumMulti(vector<int>& A, int target) {//Leetcode923:三数之和的多钟可能//initialize some constint kMod = 1e9 + 7;int kMax = 100;//calculate frequencyvector<long> freq(kMax + 1, 0);for (int a : A){freq[a]++;}long ans = 0;//for different condition calculate the result and add togetherfor (int i = 0; i <= target; i++){for (int j = i; j <= target; j++){int k = target - i -j;//checkt whether the value k is legalif (k < 0 || k >= freq.size()|| k < j) continue;//check whether the number exits in Aif (!freq[i]||!freq[j]||!freq[k]) continue;//condition 1if((i == j)&&(j == k)){ // 都相等,ans += freq[i] * (freq[i] - 1) * (freq[i] - 2)/6; // 猜想,全排列第一个数概率x 第二个数概率x-1,第三个数x-2;为了去重还需要除以 3!= 3 * 2 *1 }//condition2else if((i == j)&& (j != k)){ans += freq[k] * freq[i] * (freq[i] - 1) /2; // 这里两个数重复,除以 2! = 2* 1}//condition 3else if ((i != j) && (j == k)){ans += freq[i] * freq[j] * (freq[j] - 1) /2;}//condition 4else {ans += freq[i] * freq[j] * freq[k];}}}return ans%kMod;}