Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2)
同3sum相似。不过我用map超时。map底层是平衡二叉树,取一个元素不是O(1),也许是这个原因超时。
lass Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { //if(num.size()<=3)return NULL; vector<vector<int>> re; map<vector<int>,int> m_re; map<int,int> m; for(int i = 0 ; i < num.size(); i++) m[num[i]]++; for(map<int,int> ::iterator it4 = m.begin();it4 != m.end();it4++ ) { if(it4->second <=0)continue; int tar3 = target - it4->first; m[it4->first]--; //3sum for(map<int,int> ::iterator it3 = it4 ;it3 != m.end();it3++ ) { if(it3->second <= 0) continue; int tar2 = tar3 - it3->first; m[it3->first] --; //2sum for(map<int,int> ::iterator it2 = it3 ;it2 != m.end();it2++) { if(it2->second <= 0) continue; int tar1 = tar2 - it2->first; m[it2->first] --; if( m[tar1] >0) { vector <int>temp; temp.push_back(it4->first); temp.push_back(it3->first); temp.push_back(it2->first); temp.push_back(tar1); //sort(temp.begin(),temp.end()); //if(m_re.find(temp) == m_re.end() ) { // m_re[temp]++; re.push_back(temp); } } m[it2->first] ++; } m[it3->first] ++; } m[it4->first]++; } return re; } };
有人说有N^2的算法,通过分治算两两的和,然后再用2sum算target。不过这种方法如何排除2个两两和不是由重复元素算来的呢?没有找到源码。
新
#include<iostream> #include<iostream>