4Sum
Difficulty:mediun
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: 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] ]
求一个没排序的数组中四个数和等于目标数的组合,一开始四个数全部用递归来进行寻找,但是这样的话时间复杂度就会超过leetcode的要求,所以我先对数组进行排序,递归选择四个数中的前两个(排序为升序,递归从大到小开始选),后两个数则是在剩下的排序数组中选择两个数,可以根据目标数大小对这两个数分别从头尾开始选择,当相加数大于目标数则尾部改为用尾部减一的位置,如果相加数小于目标数则头部改为用头部加一的位置,当相加数等于目标数则就是我们要找的组合,当尾部位置一直大于头部位置时一直重复这个步骤。这样的方法能够大大减少时间负责度。
当然后来去看别人的解答发现并不需要用递归也能做出来,并且使用set可以避免重复的结果,虽然我的也符合leetcode的要求,但是还是比较麻烦。
vector<vector<int>> fourSum(vector<int>& nums, int target) {
static vector<vector<int>> *tmp = new vector<vector<int>>();//临时存放结果
static int a[4];//选取的四个数
static int k=1;//首先递归选取前两个数 即a[0] a[1]
int left, right;//选取的后两个数的位置
sort(nums.begin(), nums.end());//对输入数组进行排序
for (int i = nums.size(); i > k; i--){
a[k] = nums.at(i-1);//选取前两个数中的一个
if (k > 0){//前两个数没选完则继续选
vector<int> copy(nums);
vector<int>::iterator it = copy.begin() + i-1;
copy.erase(it);
k--;
fourSum(copy, target);//递归选取数字
k++;
}
else{//前两个数选完了
right = i - 2;
left = 0;
while (right > left){
a[2] = nums.at(right);
a[3] = nums.at(left);
int sum = a[0] + a[1] + a[2] + a[3];
if (sum == target){//找到正确的四个数
vector<int> one;
one.push_back(a[0]);
one.push_back(a[1]);
one.push_back(a[2]);
one.push_back(a[3]);
std::sort(one.begin(), one.end());//排序
tmp->push_back(one);//放入临时结果
right--;
left++;
}
else if (sum > target) right--;
else left++;
}
}
}
vector<vector<int>> result;
if (k == 1){//遍历完整个数列
result = *tmp;
std::sort(result.begin(), result.end());
result.erase(unique(result.begin(), result.end()), result.end());//去除重复的
tmp = new vector<vector<int>>();//重置tmp以便下次调用
return result;
}
else{//没遍历完整个数组返回为空
return result;
}
}