Skip to content

Commit 80b945e

Browse files
committed
数字组合
1 parent 14052a9 commit 80b945e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

combination_sum.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param candidates, a list of integers
5+
# @param target, integer
6+
# @return a list of lists of integers
7+
def combinationSum(self, candidates, target):
8+
# write your code here
9+
self.ret = []
10+
self.target = target
11+
candidates.sort()
12+
self._combinationSum(candidates, [], 0, 0)
13+
return self.ret
14+
15+
def _combinationSum(self, candidates, comb, i, _sum):
16+
if _sum == self.target:
17+
self.ret.append(comb[:])
18+
elif _sum > self.target:
19+
return
20+
else:
21+
if i <= len(candidates):
22+
comb.append(candidates[i])
23+
self._combinationSum(candidates, comb, i, _sum + candidates[i])
24+
comb.pop()
25+
prev = candidates[i]
26+
j = i
27+
while j < len(candidates):
28+
if candidates[j] != prev:
29+
prev = candidates[j]
30+
comb.append(candidates[j])
31+
self._combinationSum(candidates, comb, j, _sum + prev)
32+
comb.pop()
33+
j += 1

0 commit comments

Comments
 (0)