1. 程式人生 > >leetcode-18.4Sum 四數之和

leetcode-18.4Sum 四數之和

題目:

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]
]

給定一個包含 n 個整數的陣列 nums 和一個目標值 target,判斷 nums 中是否存在四個元素 a,

b,c 和 d ,使得 a + b + c + d 的值與 target 相等?找出所有滿足條件且不重複的四元組。

注意:

答案中不可以包含重複的四元組。

示例:

給定陣列 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

滿足要求的四元組集合為:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

思路:與2Sum, 3Sum, 3Sum Clost這幾個 題目類似。這道題首先對原陣列排序,然後固定 第一個引數i,然後固定第二個引數j=i+1,然後使用left從j+1開始往後和right從len-1開始往前找四數之和是否為target,如果 是加入輸出陣列,遍歷所有 情況, 時間複雜度為O(N^2).這裡注意要判斷不重複,我們可以借用set來去除重複。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        set<vector<int>> res;
        sort(nums.begin(),nums.end());
        int left,right,j,sum=0,len=nums.size();
        
        for(int i=0;i<len-3;++i)
        {
            for(j=i+1;j<len-2;++j)
            {
                if(j>i+1 && nums[j]==nums[j-1]) continue; //判斷元素是否相等
                left=j+1; right = len-1;
                while(left<right)
                {
                    sum=nums[i]+nums[j]+nums[left]+nums[right];
                    if(sum==target)
                    {
                        vector<int> output{nums[i],nums[j],nums[left],nums[right]};
                        res.insert(output);
                        left++;
                    }else if(sum<target) left++;
                    else right--;
                }
            }
        }return vector<vector<int>> {res.begin(),res.end()};
    }
};