【LeetCode】40. Combination Sum II 解题报告(Python)

题目分析:

这个题题目是让找不重复列表中可以组成目标值的所有组合,其中每个列表元素都只在当前组合中使用一次。他与【LeetCode】39. Combination Sum是非常相似的。不同是列表中的元素只能用一次,我们只需要想办法加上这个限定就可以了。代码中已有明确注释,不在累述。

测试代码:

class Solution:
    def combinationSum2(self, candidates, target):
        #下面有一个目标值小于某一元素就break,所以先排序
        candidates.sort()
        #储存返回的二维列表
        res, length = [], len(candidates)
        #递归,目标值,起始位置,当前组合
        def dfs(target, start, vlist):
            #目标值为0,表明当前递归完成,把当前递归结果加入res并返回
            if target == 0:
                return res.append(vlist)
            #从开始下标循环
            for i in range(start, length):
                #candidates有序,只要当前大于目标后面都大于,直接break
                if target < candidates[i]: break
                #这个判断保证不重复例如1,1,2,5,6,7,10,第二个1就会被跳过
                if i > start and candidates[i] == candidates[i - 1]: continue
                #否则目标值减当前值,i+1为新的起始位置(不用重复数字),把当前值加入当前组合
                else:   dfs(target - candidates[i], i + 1, vlist + [candidates[i]])
        dfs(target, 0, [])
        return res

print(Solution().combinationSum2(candidates = [10,1,2,7,6,1,5], target = 8))   #提交时请删除该行

猜你喜欢

转载自blog.csdn.net/L141210113/article/details/88524058