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。
難處還是在于去重的細(xì)節(jié)做法

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

反思

  • 相同的問(wèn)題,不停地出現(xiàn),作為懶惰的程序員,需要尋找規(guī)律,給出一個(gè)general solution
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,927評(píng)論 0 33
  • 案例一:實(shí)現(xiàn)全屏滑動(dòng) 案例二:去掉導(dǎo)航欄下的線 案例三:隱藏tabbar 案例三:隱藏導(dǎo)航欄返回文字 案例四:改變...
    前年的邂逅_Jerry閱讀 191評(píng)論 0 0
  • 老房子里住進(jìn)了一對(duì)河南來(lái)的中年夫婦。男的是個(gè)老實(shí)巴交的農(nóng)民,黝黑的臉,一見生人就拘謹(jǐn)?shù)卮曛p手,女的是個(gè)睜眼...
    軟軟的日子閱讀 260評(píng)論 0 0
  • 小詩(shī)和男朋友很恩愛的相戀了五年,她非常愛他男朋友,不知道是不是激情過(guò)了,生活就剩下了瑣碎,結(jié)局總是不那么美好,分了...
    一只微笑的羊閱讀 311評(píng)論 0 0
  • 我想我們每一個(gè)人都應(yīng)該在年初思考下2017年應(yīng)該怎么過(guò),怎么樣才能不比2016年過(guò)的更操蛋。這就是我分享這文章到朋...
    Sky高閱讀 407評(píng)論 4 0

友情鏈接更多精彩內(nèi)容