4Sum

Date:

  Oct 30, 2017

Problem:

  https://leetcode.com/problems/4sum/description/

Description:

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

  

  可以拓展为nSum问题。

  首先考虑2Sum,暴力检索复杂度为O(N^2)。但如果预先为数列排序,可以利用数列的有序性编写更高效的算法。

  若将数列排为升序,考虑任意一对元素nums[h], nums[t],它们的和有三种情况:

    sum < target:此时,将h右移到下一个值,使得sum的值增加,以期取到target;

    sum > target:同理,将t左移到下一个值,使得sum的值减少,以期取到target;

    sum = target:此时,将[h, t]记录,并将h,t向中间移动到下一个值。

  当头尾指针交错时,退出检索,返回记录。

  可以看到,此时,对于一个nums[h],它不需要再与其他nums[t]匹配一遍。实际上,与它匹配的只有nums[t1], nums[t2], ... , nums[tk],nums[t1]为满足nums[h]+nums[t1] < target的第一个值,nums[tk]为满足nums[h-1]+nums[tk] < target的第一个值。容易证明,任意t* < t1,nums[h]+nums[t*] < nums[h]+nums[t1] < target,nums[h]不需要再与任何下标小于t1的元素匹配。同理可以证明nums[h]不需要与任何下标大于tk的元素匹配。而h与t的地位是对称的。综上所述,我们的检索方式能够覆盖所有可能获得sum = target的数对。

  拓展为nSum问题,只需递归地化为2Sum问题即可。同时可以利用数列有序性做一些剪枝。

  以下是submission。

 1 class Solution:
 2     def findSum(self, nums, target, n, rt):
 3         if n==2:
 4             h = 0
 5             t = len(nums) - 1
 6             while h<t:
 7                 s = nums[h]+nums[t]
 8                 if s==target:
 9                     self.rs.append(rt+[nums[h],nums[t]])
10                     while h<t and nums[h+1]==nums[h]:
11                         h += 1
12                     h += 1
13                     while h<t and nums[t-1]==nums[t]:
14                         t -= 1
15                     t -= 1
16                 elif s<target:
17                     while h<t and nums[h+1]==nums[h]:
18                         h += 1
19                     h += 1
20                 else:
21                     while h<t and nums[t-1]==nums[t]:
22                         t -= 1
23                     t -= 1
24         else:
25             for i in range(len(nums)-n+1):
26                 if nums[i]*n <= target <= nums[-1]*n:
27                     if i == 0 or i > 0 and nums[i-1] != nums[i]:
28                         self.findSum(nums[i+1:], target-nums[i], n-1, rt+[nums[i]])
29                 else:
30                     return
31     def fourSum(self, nums, target):
32         nums.sort()
33         self.rs = []
34         self.findSum(nums, target, 4, [])
35         return self.rs

  附上思路相似的C++代码。作者为cx1992。传送门https://discuss.leetcode.com/topic/28641/my-16ms-c-code。

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        vector<vector<int>> total;
        int n = nums.size();
        if(n<4)  return total;
        sort(nums.begin(),nums.end());
        for(int i=0;i<n-3;i++)
        {
            if(i>0&&nums[i]==nums[i-1]) continue;
            if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) break;
            if(nums[i]+nums[n-3]+nums[n-2]+nums[n-1]<target) continue;
            for(int j=i+1;j<n-2;j++)
            {
                if(j>i+1&&nums[j]==nums[j-1]) continue;
                if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target) break;
                if(nums[i]+nums[j]+nums[n-2]+nums[n-1]<target) continue;
                int left=j+1,right=n-1;
                while(left<right){
                    int sum=nums[left]+nums[right]+nums[i]+nums[j];
                    if(sum<target) left++;
                    else if(sum>target) right--;
                    else{
                        total.push_back(vector<int>{nums[i],nums[j],nums[left],nums[right]});
                        do{left++;}while(nums[left]==nums[left-1]&&left<right);
                        do{right--;}while(nums[right]==nums[right+1]&&left<right);
                    }
                }
            }
        }
        return total;
    }
};
原文地址:https://www.cnblogs.com/neopolitan/p/7754407.html