-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathcombination-sum.py
35 lines (32 loc) · 1.19 KB
/
combination-sum.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
# coding: utf-8
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, candidates, target):
# write your code here
self.ret = []
self.target = target
candidates.sort()
self._combinationSum(candidates, [], 0, 0)
return self.ret
def _combinationSum(self, candidates, comb, i, _sum):
if _sum == self.target:
self.ret.append(comb[:])
elif _sum > self.target:
return
else:
if i <= len(candidates):
comb.append(candidates[i])
self._combinationSum(candidates, comb, i, _sum + candidates[i])
comb.pop()
prev = candidates[i]
j = i
while j < len(candidates):
if candidates[j] != prev:
prev = candidates[j]
comb.append(candidates[j])
self._combinationSum(candidates, comb, j, _sum + prev)
comb.pop()
j += 1
# medium: http://lintcode.com/zh-cn/problem/combination-sum/