[LeetCode]4Sum

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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, abcd)
  • 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)

思考:在3Sum的基础上,再加一个循环。

class Solution {

public:

    vector<vector<int> > fourSum(vector<int> &num, int target) {

        // IMPORTANT: Please reset any member data you declared, as

        // the same Solution instance will be reused for each test case.

		sort(num.begin(),num.end());

		int i,j,k,m,sum;

		vector<vector<int> > ret;

		for(i=0;i!=num.size();i++)

		{

			if(i&&num[i]==num[i-1]) continue;

			for(j=i+1;j!=num.size();j++)

			{

				if(j>i+1&&num[j]==num[j-1]) continue; 

				k=j+1;

				m=num.size()-1;

				while(k<m)

				{

					if(k>j+1&&num[k]==num[k-1])

					{

						k++;

						continue;

					}

					if(m<num.size()-1&&num[m]==num[m+1])

					{

						m--;

						continue;

					}

					sum=num[i]+num[j]+num[k]+num[m];

					if(sum==target)

					{

						vector<int> ans;

						ans.push_back(num[i]);

						ans.push_back(num[j]);

						ans.push_back(num[k]);

						ans.push_back(num[m]);

						ret.push_back(ans);

						k++;

						m--;

					}

					else if(sum<target) k++;

					else m--;				

				}

			}

		}

		return ret;

    }

};

  

你可能感兴趣的:(LeetCode)