zoukankan      html  css  js  c++  java
  • Combination Sum

    问题:给定一个无重复的数组candidates和一个目标值target,根据数组中的元素输出和为目标值的所有可能组合,数组中的每个元素可以多次使用,输出结果不能有重复的组合

    示例:

    输入:candidates = [2,3,6,8]  target = 8   

    输出:[[2,2,2,2],[2,3,3],[2,6],[8]]

    解决思路:对candidates进行遍历,相应的减少target,并使用递归的方法,直到target为0,得到和为0的组合

    Python代码:

    class Solution(object):
        def combinationSum(self, candidates, target):
            """
            :type candidates: List[int]
            :type target: int
            :rtype: List[List[int]]
            """
            self.out = []
            self.Sum(candidates,target)
            return self.out
            
        def Sum(self,candidates,target,res=[]):
            if not target:
                self.out.append(res)
                return
            for i in range(len(candidates)):
                can = candidates[i]
                if can <= target:
                    self.Sum(candidates[i:],target-can,res+[can]) # To avoid duplicate combinations, input "candidaters[i:] instead of candidates"
  • 相关阅读:
    模拟22
    模拟21
    模拟20
    模拟19
    晚测11
    Redis 内存模型
    Redis AOF重写
    基础省选题选做
    八年级上 期中考试祭
    P2049 魔术棋子 题解
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10811540.html
Copyright © 2011-2022 走看看