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)

  原理同Two Sum,直接上代码:

solution:

vector<vector<int> > fourSum(vector<int> &num, int target) {
    int n = num.size();
    vector<vector<int> > res;
    if(n < 4)
        return res;
    sort(num.begin(),num.end());
    vector<int> temp(4);
    int low, high;
    int sum;
    for (int i = 0;i < n-3;++i)
    {
        for (int j = i+1;j < n-2;++j)
        {
            sum = target - num[i] - num[j];
            low = j + 1;
            high = n - 1;
            while (low < high)
            {
                if (num[low] + num[high] == sum)
                {
                    temp[0] = num[i];
                    temp[1] = num[j];
                    temp[2] = num[low];
                    temp[3] = num[high];
                    res.push_back(temp);
                    ++low;
                    --high;
                    while (low < high && num[low] == num[low-1])
                        ++low;
                    while (low < high && num[high] == num[high+1])
                        --high;
                }
                else if (num[low] + num[high] < sum)
                    ++low;
                else
                    --high;
            }
            while (j+1 < n-2 && num[j+1] == num[j])
                ++j;
        }
        while (i+1 < n-3 && num[i+1] == num[i])
            ++i;
    }
    return res;
}

总结

      Two Sum:  http://www.cnblogs.com/gattaca/p/4122041.html

        3Sum:  http://www.cnblogs.com/gattaca/p/4281581.html

3Sum Closest:  http://www.cnblogs.com/gattaca/p/4284708.html

           kSum:  http://tech-wonderland.net/blog/summary-of-ksum-problems.html

posted @ 2015-02-11 10:15  Sawyer Ford  阅读(125)  评论(0编辑  收藏  举报