-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCombinationSum_v0.py
More file actions
39 lines (29 loc) · 866 Bytes
/
CombinationSum_v0.py
File metadata and controls
39 lines (29 loc) · 866 Bytes
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
#!/usr/bin/env python
# encoding: utf-8
class Solution:
# @param {integer[]} candidates
# @param {integer} target
# @return {integer[][]}
def combinationSum(self, candidates, target):
candidates.sort()
return combination(candidates, target)
def combination(candidates, target):
if target < 0:
return []
if target == 0:
return [[]]
r = []
for i, n in enumerate(candidates):
items = combination(candidates[i:], target - n)
for item in items:
if not item or item[-1] <= n:
item.append(n)
else:
item = [n] + item
r.append(item)
return r
if __name__ == '__main__':
s = Solution()
print s.combinationSum([2,3,6,7], 7)
print s.combinationSum([8,7,4,3], 11)
print s.combinationSum([3,2,6,7], 11)