動機
有剪枝差太多
Problem
Given an array nums
of n
integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]]
such that:
- t
0 <= a, b, c, d < n
ta
,b
,c
, andd
are distinct. tnums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Example 1:
Input: nums = [1,0,-1,0,-2,2], target = 0Output: [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input: nums = [2,2,2,2,2], target = 8Output: [[2,2,2,2]]
Constraints:
- t
1 <= nums.length <= 200
t-109 <= nums[i] <= 109
t-109 <= target <= 109
Sol
在k是大於2時,就用backtrack去生剩下的(k-1)sum,最後就是2sum
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
def sumk(ns, target, k):
if len(ns) <= 1 or k <= 1 or ns[0]*k > target or target > ns[-1] *k:
return []
elif k == 2:
return sum2(ns,target)
else:
ret = []
for i in range(len(ns)):
if i == 0 or ns[i-1] != ns[i]:
subs = sumk(ns[i+1:],target-ns[i], k-1)
if subs:
ret += [[ns[i]]+sub for sub in subs]
return ret
def sum2(ns,target):
ret = []
a,b = 0, len(ns)-1
while a<b:
cnt = ns[a]+ns[b]
if cnt == target:
ret.append([ns[a],ns[b]])
while a <= b-1 and ns[b-1] == ns[b]:
b -= 1
while a+1 <= b and ns[a+1] == ns[a]:
a += 1
a,b = a+1, b-1
elif cnt > target:
while a <= b-1 and ns[b-1] == ns[b]:
b -= 1
b -= 1
else:
while a+1 <= b and ns[a+1] == ns[a]:
a += 1
a += 1
return ret
nums.sort()
return sumk(nums,target,4)