Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> finalResult;
int len = nums.size();
if(len <= 3)
return finalResult;
else
sort(nums.begin(), nums.end());
for(int i = 0; i< len - 3;)
{
int a = nums[i];
for(int j = i+1; j < len - 2;)
{
int b = nums[j];
for(int p = j + 1, q = len-1; p < q;)
{
int c = nums[p], d = nums[q];
int value = a + b + c + d;
if(value == target)
{
finalResult.push_back({a,b,c,d});
while(d == nums[--q] );
while(c == nums[++p]);
}
else if(value > target){
while(d == nums[--q] );
}
else{
while(c == nums[++p]);
}
}
j++;
while(nums[j-1] == nums[j]&& j<len - 2)
j++;
}
i++;
while(nums[i - 1] == nums[i] && i< len -3)
i++;
}
return finalResult;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment