Note: The Listed platform will permanently shut down December 31, 2026. Your data published on Listed will still be available in your personal Standard Notes account. Learn more

NSum

NSum

Leetcode 里面有一个NSum问题

解法的话

两数之和就是用 2 pointer

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        left = 0
        n = len(nums)
        right = n-1
        res = []

        while left < right:
            l = nums[left]
            r = nums[right]
            if l+r == target:
                res.append([left,right])
                left += 1
                right -= 1
                while nums[left] == nums[left-1] and left < right:
                    left += 1
                while nums[right] == nums[right+1] and right> left:
                    right -=1

            elif l+r > target:
                right -= 1
                while nums[right] == nums[right+1] and right> left:
                    right -=1

            else:
                left += 1
                while nums[left] == nums[left-1] and left < right:
                    left += 1
        return res

ThreeSum  就是再加一层loop

 FourSum 就是再 ThreeSum 的基础上再加一层loop

但是,如果出现了一个 100SUM  的时候,手就要写断了吧

这个时候,我们其实直接call上面的 TwoSum 就可以了

那么我们的 NSum function如下

    def NSum(self, nums, n, target):
        nums.sort()
        res = []
        if n == 2:
            return self.twoSum(nums, target)
        else:
            for i, num in enumerate(nums):
                if i>0 and num == nums[i-1]:
                    continue
                else:
                    n_1_sum = self.NSum(nums[i+1:], n-1, target-num)
                    if len(n_1_sum)>0:
                        for temp in n_1_sum:
                            res.append(temp+[num])
        return res

Target可以是任何值,包括0

这个时候,我们的 threeSum  和 FourSum  包括 100Sum 直接call这个function就可以了

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:

        return self.NSum(nums, 3, 0)

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:

        return self.NSum(nums, 4, target)

100 SUM

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:

        return self.NSum(nums, 100, target)


You'll only receive email when they publish something new.

More from LeetCode
All posts