Skip to content

Commit 0307940

Browse files
committed
数字组合 II
1 parent 80b945e commit 0307940

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

combination_sum_ii.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
"""
5+
@param candidates: Given the candidate numbers
6+
@param target: Given the target number
7+
@return: All the combinations that sum to target
8+
"""
9+
def combinationSum2(self, candidates, target):
10+
# write your code here
11+
self.ret = []
12+
self.target = target
13+
candidates.sort()
14+
self._combinationSum2(candidates, [], 0, 0)
15+
return self.ret
16+
17+
def _combinationSum2(self, candidates, comb, i, _sum):
18+
if _sum == self.target:
19+
self.ret.append(comb[:])
20+
elif _sum > self.target:
21+
return
22+
else:
23+
if i <= len(candidates):
24+
prev = None
25+
j = i
26+
while j < len(candidates):
27+
if candidates[j] != prev:
28+
prev = candidates[j]
29+
comb.append(candidates[j])
30+
self._combinationSum2(candidates, comb, j + 1, _sum + prev)
31+
comb.pop()
32+
j += 1

0 commit comments

Comments
 (0)