先给出一个使用回溯法,求“组合”,但是这种方案会TLE:
1 class Solution: 2 def __init__(self): 3 self.filter = set() 4 self.result = [] 5 6 def trackBack(self,nums,i,temp,target): 7 if len(temp) == 4: 8 cursum = nums[temp[0]] + nums[temp[1]] + nums[temp[2]] + nums[temp[3]] 9 if cursum == target: 10 k = (nums[temp[0]] , nums[temp[1]] , nums[temp[2]] , nums[temp[3]]) 11 if k not in self.filter: 12 self.filter.add(k) 13 self.result.append([nums[temp[0]] , nums[temp[1]] , nums[temp[2]] , nums[temp[3]]]) 14 return 15 for j in range(i,len(nums)): 16 if j not in temp: 17 temp.append(j) 18 self.trackBack(nums,j,temp,target) 19 temp.pop(-1) 20 21 def fourSum(self, nums: 'List[int]', target: int) -> 'List[List[int]]': 22 nums = sorted(nums) 23 temp = [] 24 self.trackBack(nums,0,temp,target) 25 return self.result
下面给出一个AC的参考的答案,
1 class Solution: 2 def fourSum(self, nums, target): 3 nums.sort() 4 results = [] 5 self.findNsum(nums, target, 4, [], results) 6 return results 7 8 def findNsum(self, nums, target, N, result, results): 9 if len(nums) < N or N < 2: return 10 11 # solve 2-sum 12 if N == 2: 13 l,r = 0,len(nums)-1 14 while l < r: 15 if nums[l] + nums[r] == target: 16 results.append(result + [nums[l], nums[r]]) 17 l += 1 18 r -= 1 19 while l < r and nums[l] == nums[l - 1]: 20 l += 1 21 while r > l and nums[r] == nums[r + 1]: 22 r -= 1 23 elif nums[l] + nums[r] < target: 24 l += 1 25 else: 26 r -= 1 27 else: 28 for i in range(0, len(nums)-N+1): # careful about range 29 if target < nums[i]*N or target > nums[-1]*N: # take advantages of sorted list 30 break 31 if i == 0 or i > 0 and nums[i-1] != nums[i]: # recursively reduce N 32 self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results) 33 return
这题相当于是在两个数的基础上增加两层循环,或是在三个数的基础上增加一层循环,对之前的“基础前置”题目记不住,这道题就很难写出来。
这道题目难度属于Medium,是对于已经掌握了之前的两道题目的人来划分的。
如果做题的人没有之前的基础,没有做过之前那两道题,那就是hard级别了。