给你四个整数数组 nums1、nums2、nums3 和 nums4 ,数组长度都是 n ,请你计算有多少个元组 (i, j, k, l) 能满足:
0 <= i, j, k, l < n
nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/4sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这题可以使用两种解题思路,第一种是进制的方法(也就相当于四个for循环),四个数组,一个数组有n个数,这样总共的可能就是n的4次方,这样可以用一个4位n进制的数来表示每个数组取得是哪个数。
第二种方法就是使用hash表,因为这题只需要找出和为0的组合的个数,也不需要去重,所以可以用两个for循环来遍历 num1和num2,把和当作unordered_map的key存入并且把当前位置的值加一,再用同样的方法遍历剩余的两个数组,求出两个数的和SUM,然后再map中查找-SUM,如果能找到,这把res的值加上对应的value值,否则继续遍历。
#includetips#include #include using namespace std; class Solution1 { public: int fourSumCount(vector & nums1, vector & nums2, vector & nums3, vector & nums4) { int index[4] = {0,0,0,0}; int n = nums1.size(); int end = n * n * n * n; int res = 0; for(int i = 0 ;i < end ;i++){ getIndex(i,n,index); if(nums1[index[0]] + nums2[index[1]] + nums3[index[2]] + nums4[index[3]] == 0){ //printf("*%2d,%2d,%2d,%2dn",index[0],index[1],index[2],index[3]); //printf("%2d,%2d,%2d,%2dn",nums1[index[0]],nums2[index[1]],nums3[index[2]],nums4[index[3]]); res++; } } return res; } void getIndex(int num ,int n, int* p){ for( int i = 0; i < 4; i++){ p[i] = num % n; num = num / n; } } }; class Solution2 { public: int fourSumCount(vector & A, vector & B, vector & C, vector & D) { unordered_map umap; //key:a+b的数值,value:a+b数值出现的次数 // 遍历大A和大B数组,统计两个数组元素之和,和出现的次数,放到map中 for (int a : A) { for (int b : B) { umap[a + b]++; } } int count = 0; // 统计a+b+c+d = 0 出现的次数 // 在遍历大C和大D数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。 for (int c : C) { for (int d : D) { if (umap.find(0 - (c + d)) != umap.end()) { count += umap[0 - (c + d)]; } } } return count; } }; int main(){ Solution1 solution1; vector nums1 {1,2}; vector nums2 {-2,-1}; vector nums3 {-1,2}; vector nums4 {0,2}; // int index[4]; // solution.getIndex(15,2,index); // for(auto i : index){ // printf("%2d,", i); // } printf("%2dn", solution1.fourSumCount(nums1,nums2,nums3,nums4)); Solution2 solution2; printf("%2dn", solution2.fourSumCount(nums1,nums2,nums3,nums4)); return 0; }
这题就是要注意与三数之和,四数之和相区分,本题是不需要考虑组合里面值重复的问题的,适合用hash法。而三数之和,四数之和这两个题是需要考虑值重复的问题的,适合用回溯法。



