4Sum

Code:

class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        vector<int> buf;
        vector<vector<int>> res;
        if(num.size()<4) return res;
        sort(num.begin(),num.end());
        int n=num.size();
        int p,q,i,j;
        for(p=0;p<n-3;p++)
        {
            for(q=n-1;q>p+2;q--)
            {
                i=p+1;
                j=q-1;
                while(i<j)
                {
                    if(num[i]+num[j]+num[p]+num[q]==target)
                    {
                        buf.clear();
                        buf.push_back(num[p]);
                        buf.push_back(num[i]);
                        buf.push_back(num[j]);
                        buf.push_back(num[q]);
                        res.push_back(buf);
                        i++;
                        j--;
                        while(i<j&&num[i-1]==num[i]) i++;
                        while(i<j&&num[j]==num[j+1]) j--;
                    }
                    else if(num[i]+num[j]+num[p]+num[q]<target)
                        i++;
                    else
                        j--;
                }
                while(q>p+2&&num[q]==num[q-1])
                    q--;
            }
            while(p<n-3&&num[p]==num[p+1])
                p++;
        }
        return res;
        
    }
};

 

posted @ 2013-10-30 07:44  WinsCoder  阅读(165)  评论(0编辑  收藏  举报