-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombinationSum.py
50 lines (41 loc) · 1.12 KB
/
CombinationSum.py
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# https://www.interviewbit.com/problems/combination-sum/
from functools import cmp_to_key
def generate(nums, curIndex, result, soFar, target):
if target == 0:
result.append(soFar.copy())
return
if target < 0 or curIndex >= len(nums):
return
soFar.append(nums[curIndex])
generate(nums, curIndex, result, soFar, target - nums[curIndex])
soFar.pop()
generate(nums, curIndex + 1, result, soFar, target)
def cmpFf(ls1, ls2):
i = 0
while i < len(ls1) and i < len(ls2):
if ls1[i] < ls2[i]:
return -1
if ls1[i] > ls2[i]:
return -1
if len(ls1) == len(ls2):
return 0
elif i >= len(ls1):
return -1
else:
return 1
def removeDuplicates(A):
st = set(A)
A.clear()
for elem in st:
A.append(elem)
class Solution:
# @param A : list of integers
# @param B : integer
# @return a list of list of integers
def combinationSum(self, A, B):
removeDuplicates(A)
A.sort()
result = []
soFar = []
generate(A, 0, result, soFar, B)
return result