3. 回溯

1. 组合总数


class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        path = []
        candidates.sort()
        self.dfs(candidates, path, res, target, 0)
        return res

    def dfs(self, candidates, path, res, target, start):
        if target < 0:
            return
        if target == 0:
            # res.append(path[:])
            cur = path[:]
            cur.sort()
            if cur not in res:
                res.append(cur)
        for i in range(start, len(candidates)):
            cur = candidates[i]
            if cur > target:
                return
            if i > 0 and cur == candidates[i - 1]:
                continue
            path.append(cur)
            self.dfs(candidates, path, res, target - cur, start)
            path.pop()

2. 组合总数2

40

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        res = []
        path = []
        candidates.sort()
        self.dfs(target, path, res, candidates, 0)
        if sum(candidates) < target:
            return []
        return res

    def dfs(self, target, path, res, candidates, start):
        if target < 0:
            return
        if target == 0:
            cur = path[:]
            cur.sort()
            if cur not in res:
                res.append(cur)

        for i in range(start, len(candidates)):
            if candidates[i] > target:
                break
            if i > start and candidates[i] == candidates[i - 1]:
                continue
            path.append(candidates[i])
            self.dfs(target - candidates[i], path, res, candidates, i + 1)
            path.pop()
posted @ 2021-12-16 14:45  _无支祁  阅读(46)  评论(0)    收藏  举报