leetcode.array--40. Combination Sum II

来源:互联网 发布:windows账户有什么用 编辑:程序博客网 时间:2024/05/20 04:09

问题:40. Combination Sum II

问题描述:https://leetcode.com/problems/combination-sum-ii/description/

题目意思是说,从一个给定的序列中找出相加等于target的组合,要求每一个元素只能使用一次,这个以前用C写过不少啦,DFS如下:

Python:

class Solution(object):    def combinationSum2(self, candidates, target):        """        :type candidates: List[int]        :type target: int        :rtype: List[List[int]]        """        vis=[]        for i in range(len(candidates)):            vis.append(0)        def dfs(nums,target,path,res):            if target<0:                return            if target==0 and path not in res:                return res.append(path)            for i in range(len(nums)):                if vis[i]!=0 or target<nums[i]:                    return                else:                    vis[i]=1                    dfs(nums,target-nums[i],path+[nums[i]],res)                    vis[i]=0        res=[]        dfs(sorted(candidates),target,[],res)        return  res


原创粉丝点击