4Sum

Given an array S of n integers, are there elements abc, 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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • 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)
 
 
<pre name="code" class="cpp">#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void foursum(vector<int>&a, int target, vector<vector<int>>&result);


int main()
{

	vector<int>a = { -1, 0, 1,0, 2, -2};

	int target = 0;
	vector<vector<int>> result;
	foursum(a, 0, result);


	cout << result.size() << endl;
	for (int i = 0; i < result.size(); i++)
	{
		for (int j = 0; j<result[i].size();j++)
		{
			cout << result[i][j] << endl;
		}
	}
	system("pause");
	return 0;
}

void foursum(vector<int>& a, int target, vector<vector<int>>& result)
{
	sort(a.begin(), a.end());
	int m, n;
	int temp;
	for (int i = 0; i < a.size(); i++)
	{
		if (i>0 && a[i] == a[i - 1])
		{
			continue;
		}
		for (int j = i + 1; j < a.size(); j++)
		{
			if (j>i + 1 && a[j] == a[j - 1])
			{
				continue;
			}
			m = j + 1;
			n = a.size() - 1;
			while (m < n)
			{
				if (m>j + 1 && a[m] == a[m - 1])
				{
					m++;
					continue;
				}
				if (n < a.size() - 1 && a[n] == a[n + 1])
				{
					n--;
					continue;
				}
				temp = a[i] + a[j] + a[m] + a[n];
				if (temp == target)
				{
					vector<int>d;
					d.push_back(a[i]);
					d.push_back(a[j]);
					d.push_back(a[m]);
					d.push_back(a[n]);
					result.push_back(d);
					m++;

				}
				else if (temp < target)
					m++;
				else
				{
					n--;
				}

			}
		}
	}
}


 
 
 

你可能感兴趣的:(4Sum)