DFS python solution


  • 0
    B
    def combinationSum2(self, candidates, target):
        candidates.sort()
        path = []
        res= []
        index = 0
        self.dfs(candidates, target, index, path, res)
        return res
        
    def dfs(self, nums, target, index, path, res):
        if target < 0:
            return
        if target == 0:
            if path not in res:
                res.append(path)
            return
        for i in range(index, len(nums)):
            if i == len(nums) - 1:
                self.dfs([], target-nums[i], 0, path+[nums[i]], res)
            else:
                self.dfs(nums, target-nums[i], i+1, path+[nums[i]], res)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.