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, 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)

思路:
1、和三個數之和兩個數之和一樣,只不過是多加了個循環而已;
代碼:

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector<vector<int>> res;
        if(num.size()<4) return res;
        sort(num.begin(),num.end());
        int sum=0;
        set<vector<int>> help;
        for(int i=0;i<=num.size()-1;i++)
        {
            for(int j=i+1;j<=num.size()-1;j++)
            {
                int start=j+1;
                int end=num.size()-1;
                while(start<end)
                {
                    sum=num[i]+num[j]+num[start]+num[end];
                    if(sum==target)
                    {
                        vector<int>tmp;
                        tmp.push_back(num[i]);
                        tmp.push_back(num[j]);
                        tmp.push_back(num[start]);
                        tmp.push_back(num[end]);
                        //res.push_back(tmp);
                        help.insert(tmp);
                        start++;
                        end--;
                    }
                    else if(sum<target) start++;
                    else end--;
                }

            }
        }
        set<vector<int>> :: iterator it=help.begin();
        for(;it!=help.end();it++)
        {
            res.push_back(*it);
        }
        return res;
    }
};
發佈了19 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章