囧, 就在3sum上面的基础上改一下就好了
class vector_int_hash{
const static int P = 10007;
const static int MOD = 1e9 + 7;
public:
size_t operator() (const vector<int> &v)const{
long long now = 0;
for(int i = 0; i < v.size(); ++ i)
now = (now * P + v[i] ) % MOD;
return now;
}
};
class vector_int_comp{
public:
int operator() (const vector<int> &a, const vector<int> & b)const{
if(a.size() != b.size())
return 0;
for(int i = 0; i < a.size(); ++ i)
if(a[i] != b[i])
return 0;
return 1;
}
};
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(num.begin(), num.end());
vector<vector<int> > ans;
//map<vector<int>, bool> hash;
unordered_map<vector<int>, bool,vector_int_hash,vector_int_comp> hash;
for(int i = 0; i + 3 < num.size(); ++ i)
for(int j = i + 1; j + 2< num.size(); ++ j)
for(int k = j + 1; k + 1 < num.size(); ++ k){
int tar = target - (num[i] + num[j] + num[k]);
int low = k + 1, high = num.size() - 1,mid;
while(low <= high)
if(num[mid = low + high >> 1] >= tar) high = mid - 1;else low = mid + 1;
if(low < num.size() && num[low] == tar){
vector<int> v;
v.push_back(num[i]);
v.push_back(num[j]);
v.push_back(num[k]);
v.push_back(tar);
if(hash.find(v) != hash.end())
continue;
hash[v] = true;
ans.push_back(v);
}
}
return ans;
}
};