040 Combination Sum II

040 Combination Sum II 

这道题是 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

 

posted @ 2015-07-18 02:30  dapanshe  阅读(107)  评论(0编辑  收藏  举报