标签:开始 color bsp app append TE for 思路 def
思路为将N sum 转换为N-1 Sum, 直到转换为 2 Sum. 不过最开始就已经将nums sort一下, 然后再处理.
def findNsum(nums, target, N, temp, ans): if len(nums) < N or N < 2 or target < nums[0]*N or target > nums[-1]*N: return if N == 2: l, r = 0, len(nums) -1 while l < r: s = nums[l] + nums[r] if s == target: ans.append(temp + [nums[l] , nums[r]]) while l < r and nums[l] == nums[l+1]: l += 1 while l < r and nums[r] == nums[r-1]: r -= 1 l += 1 r -= 1 elif s < target: l += 1 else: r -= 1 else: for i in range(len(nums) - N + 1): if i == 0 or nums[i] != nums[i-1]: # delete the same ans findNsum(nums[i+1:], target - nums[i], N -1, temp + [nums[i]], ans) # if want to call it, for example, 4 Sum, ans = [] findNsum(sorted(nums), target, 4, [] , ans) return ans
[LeetCode] Template to N Sum for (LC 15. 3Sum, LC 18. 4Sum)(N>2)
标签:开始 color bsp app append TE for 思路 def
原文地址:https://www.cnblogs.com/Johnsonxiong/p/9206889.html