Description:
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] ]
Solution:
Analysis and Thinking:
题目要求在给定一个数组S以及target数的情况下,能否在数组中找到不重复的四元组,使得和为target。这其实是在3Sum的基础上进行修改的,同样先对数组排序,然后在最外层多加一层循环
Steps:
step 1:获取数组长度、起始位置等初始信息
step 2:对数组进行排序
step 3:先确定两个元素,即前两个元素a,b,为start以及end作下标确定的数组元素
step 4:利用二分查找的方法,取得四个元素的和,如果和大于目标值,end--,如果小于目标值,start++,从而实现每次将查找范围减少一半的目的
step 5:将目标值存入暂存结果的容器,最后利用set进行去重,返回结果
Codes:
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
int i,j,startPos,endPos;
int length = num.size();
vector<int> resultElements;
vector<vector<int>> results;
set<vector<int>> resultSets;
sort(num.begin(),num.end());
for(i = 0;i < length-3;i++)
{
for(j = i + 1;j < length - 2;j++)
{
startPos = j + 1;
endPos = length - 1;
while(startPos < endPos)
{
int tempSum = num[i] + num[j] + num[startPos] + num[endPos];
if(target == curSum)
{
resultElements.clear();
resultElements.push_back(num[i]);
resultElements.push_back(num[j]);
resultElements.push_back(num[startPos]);
resultElements.push_back(num[endPos]);
resultSets.insert(resultElements);
startPos ++;
endPos --;
}
else if(target > curSum)
{
startPos ++;
}
else{
endPos --;
}
}
}
}
resultSet<vector<int>>::iterator record = resultSets.begin();
for(; record != resultSets.end(); record++)
results.push_back(*record);
return results;
}
};