LeetCode算法系列:18. 4Sum

版权声明:由于一些问题,理论类博客放到了blogger上,希望各位看官莅临指教https://efanbh.blogspot.com/;本文为博主原创文章,转载请注明本文来源 https://blog.csdn.net/wyf826459/article/details/81915085

题目描述:

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [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]
]

算法描述:

前面已经做过好多类似的题目,2sum,3sum等,这个题可以看成是原来题目的加强版,这里在2sum题目的基础上改造,即先排序,然后在二重for循环内求2sum的解。在我们选定两个数(a,b)后,题目就变成了在剩余数据中寻找和为target - a -b的2Sum解。

具体:

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> res;
        int n = nums.size();
        if(n < 4) return res;
        vector<int> oneres(4);
        sort(nums.begin(),nums.end());
        for(int i = 0; i < n - 3;i ++)
        {
            //优化,如果出现这种情况说明在当前的i之后已经不会再出现合适的解了
            if(nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) break;
            //优化,如果出现这种情况,说明当前的i值没有对应的解
            if(nums[i] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target) continue;
            for(int j = i + 1; j < n - 2; j ++)
            {
                //2sum
                //下面两句,类似于前面的优化,解释同上
                if(nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) break;
                if(nums[i] + nums[j] + nums[n - 1] + nums[n - 2] < target) continue;
                int fsum = nums[i] + nums[j];
                int bsum = target - fsum;
                for(int k = j + 1, m = n - 1; k < m; )
                {
                    if(nums[k] + nums[m] == bsum)
                    {
                        oneres[0] = nums[i], oneres[1] = nums[j], oneres[2] = nums[k], oneres[3] = nums[m];
                        res.push_back(oneres);
                        while(k < m && nums[k + 1] == nums[k])k ++;
                        while(k < m && nums[m - 1] == nums[m])m --;
                        k ++, m --;
                    }
                    else if(nums[k] + nums[m] > bsum) m --;
                    else k ++;
                }
                while(j < n - 2 && nums[j + 1] == nums[j])j ++;
            }
            while(i < n - 3 && nums[i + 1] == nums[i])i ++;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/wyf826459/article/details/81915085