关于leetcode 2sum、3sum、4sum到ksum的情况分析

通过#2sum,#3sum,#4sum
推广到ksum的情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):

def findKsum(self, nums, target, N, result, results):
if len(nums) < N or N<2 or target < nums[0]*N or target>nums[-1]*N :
return []
if N ==2:
l=0
r = len(nums)-1
while l<r:
s = nums[l]+nums[r]
if s == target:
results.append(result + [nums[l], nums[r]])
l +=1
while l<r and nums[l]==nums[l-1]:
l += 1
elif s<target:
l+=1
else:
r-=1
else:
for i, x in enumerate(nums[:-(N-1)]):
if i>0 and nums[i]==nums[i-1]:
continue
self.findKsum(nums[i+1:], target - x, N-1, result + [x], results)
return results