LeetCode-18 - 4sum

Given an array S of n integers, are there elements a, b, c, 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]
]

Solution1

利用3sum的算法,完善4sum。
难处还是在于去重的细节做法

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        result = []
        nums.sort()
        for i in range(len(nums) - 3):
            if i >= 1 and nums[i] == nums[i - 1]: continue
            for j in range(i + 1, len(nums) - 2):
                if j >= 2 and i != j - 1 and nums[j] == nums[j - 1]: continue
                k, l = j + 1, len(nums)-1
                while(k < l):
                    #print i, j, k, l
                    #print nums, nums[i], nums[j], nums[k], nums[l]
                    sum = nums[i] + nums[j] + nums[k] + nums[l]
                    if sum > target:
                        l -= 1
                    elif sum < target:
                        k += 1
                    else:
                        result.append([nums[i], nums[j], nums[k], nums[l]])
                        while(k < l) and nums[k] == nums[k + 1]:
                            k += 1
                        while(k < l) and nums[l] == nums[l - 1]:
                            l -= 1
                        l -= 1
                        k += 1

        return result

Solution2

从2sum, 3sum的做法朝后看,使用递归完成Nsum。

def fourSum(self, nums, target):
    def findNsum(nums, target, N, result, results):
        if len(nums) < N or N < 2 or target < nums[0]*N or target > nums[-1]*N:  # early termination
            return
        if N == 2: # two pointers solve sorted 2-sum problem
            l,r = 0,len(nums)-1
            while l < r:
                s = nums[l] + nums[r]
                if s == target:
                    results.append(result + [nums[l], nums[r]])
                    l += 1
                    while l < r and nums[l] == nums[l-1]:
                        l += 1
                elif s < target:
                    l += 1
                else:
                    r -= 1
        else: # recursively reduce N
            for i in range(len(nums)-N+1):
                if i == 0 or (i > 0 and nums[i-1] != nums[i]):
                    findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)

    results = []
    findNsum(sorted(nums), target, 4, [], results)
    return results

反思

  • 相同的问题,不停地出现,作为懒惰的程序员,需要寻找规律,给出一个general solution
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,787评论 0 33
  • 案例一:实现全屏滑动 案例二:去掉导航栏下的线 案例三:隐藏tabbar 案例三:隐藏导航栏返回文字 案例四:改变...
    前年的邂逅_Jerry阅读 173评论 0 0
  • 老房子里住进了一对河南来的中年夫妇。男的是个老实巴交的农民,黝黑的脸,一见生人就拘谨地搓着双手,女的是个睁眼...
    软软的日子阅读 234评论 0 0
  • 小诗和男朋友很恩爱的相恋了五年,她非常爱他男朋友,不知道是不是激情过了,生活就剩下了琐碎,结局总是不那么美好,分了...
    一只微笑的羊阅读 259评论 0 0
  • 我想我们每一个人都应该在年初思考下2017年应该怎么过,怎么样才能不比2016年过的更操蛋。这就是我分享这文章到朋...
    Sky高阅读 358评论 4 0