4 Sum
要点:
- recursion + k sum:可以用combination sum的思路,只要增加一个k的arg:因为k和i是联动的,所以recursion每层的k要-1
- 这题的success终止条件是k0 and target0,而failure的终止条件是k==0 or 过界 or target不符合条件。这里target不符合条件可以根据k来优化,类似Restore IP Addresses。利用nums是sorted,剩余的target的可能范围是[nums[i]N,nums[-1]N],即最小/最大*N。如果target超过这个范围,就可以提前返回了。
- 优化:循环终止边界是len-k+1
- 这题如果只用recursion结束会TLE,而最后需要k=2然后用双指针。
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results
def findNsum(self, nums, target, N, result, results):
if len(nums) < N or N < 2: return
# solve 2-sum
if N == 2:
l,r = 0,len(nums)-1
while l < r:
if nums[l] + nums[r] == target:
results.append(result + [nums[l], nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
while r > l and nums[r] == nums[r + 1]:
r -= 1
elif nums[l] + nums[r] < target:
l += 1
else:
r -= 1
else:
for i in range(0, len(nums)-N+1): # careful about range
if target < nums[i]*N or target > nums[-1]*N: # take advantages of sorted list
break
if i == 0 or i > 0 and nums[i-1] != nums[i]: # recursively reduce N
self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)
return