思路:中等难度题,在数组中找出不同的四个数加起来=target,目前想到两种解法,1.暴力求解此处不说,2.排序后用dfs加剪枝的方法完成(最后删除重复的四元组)
注意:这题错了不少次,需要注意以下几点,1.因为有正负数,所以判断时不能以零做基准,2.超出int限制,需用long long,3。这代码多次修改,比较不规范,而且时间卡的很死,几乎快要过不去,给大家做个参考,属于比较慢的算法。
代码:
class Solution {
public:
vector<vector<int>> an;
vector<vector<int>> an2;
vector <long long> num;
map <string, vector<int>> an1;
long long last[3];
long long value[4];
long long tar;
long long l;
vector<vector<int>> fourSum(vector<int>& nums, int target) {
l = nums.size();
int cnt = 0;
for(int i = 0; i < l; i++){
if(i > 0 && nums[i] == nums[i-1]){
cnt++;
}else{
cnt = 1;
}
if(cnt >= 5)
continue;
num.push_back(nums[i]);
}
l = num.size();
// cout << l << endl;
if(l < 4)
return an;
sort(num.begin(), num.end());
last[0] = num[l-1];
last[1] = last[0] + num[l-2];
last[2] = last[1] + num[l-3];
tar = target;
for(int i = 0; i < l; i++){
value[0] = num[i];
dfs(1, i, num[i]);
}
int l2 = an.size();
for(int i = 0; i < l2; i++){
for(int j = i - 1; j >= 0; j--){
if(an[i] == an[j]){
an.erase(an.begin() + i);
i--;
l2--;
break;
}
}
}
return an;
}
void dfs(int nowLevel, int index, long long nowValue){
if(index >= l || nowLevel >= 5){
return;
}
if(nowLevel < 4){
if(nowValue + last[3 - nowLevel] < tar){
return;
}
}
if(nowLevel == 4){
if(nowValue == tar){
vector <int> tempAn;
for(int i = 0; i < 4; i++){
tempAn.push_back(value[i]);
}
an.push_back(tempAn);
}
return;
}
for(int i = index + 1; i < l; i++){
value[nowLevel] = num[i];
dfs(nowLevel + 1, i, nowValue + num[i]);
}
}
bool compare(vector<int> a, vector<int> b){
for(int i = 3; i > 0; i--){
if(a[i] != b[i]){
return false;
}
}
return true;
}
};