这道题是 039 Combination Sum 的延伸, 稍作改动就好
class Solution: # @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum2(self, candidates, target): candidates.sort() ans = [] self.help(candidates, target, [], -1, ans) return ans def help(self, a, target, cur, s, ans): if target == 0: ans.append(cur[:]) if target < 0: return s += 1 while s < len(a): cur.append(a[s]) r = self.help(a, target - a[s], cur, s, ans) cur.pop() while s + 1 < len(a) and a[s+1] == a[s]: s += 1 if target - a[s] < 0: break s += 1
时间: 2024-12-23 05:22:01