zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第39题:给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。

    题目:

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    candidates 中的数字可以无限制重复被选取。

    说明:

    所有数字(包括 target)都是正整数。
    解集不能包含重复的组合。 

    思路:使用递归的思想,回溯和减枝

    程序:

    class Solution:
        def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
            candidates.sort()
            length = len(candidates)
            if length <= 0:
                return 
            result = []
            temp_result = []
            def auxiliary(index, temp_result, target):
                if target == 0:
                    result.append(temp_result)
                    return
                if index == length or target < candidates[index]:
                    return
                auxiliary(index, temp_result + [candidates[index]], target - candidates[index])
                auxiliary(index + 1, temp_result, target)
            auxiliary(0, temp_result, target)
            return result
  • 相关阅读:
    【设计模式】适配器模式
    【设计模式】原型模式
    【设计模式】建造者模式
    【设计模式】抽象工厂模式
    我的稳定的SpingBoot项目依赖
    Vue中使用iconfont
    Vue-兄弟组件传值
    CSS让高度百分百的方案
    css修改overflow滚动条默认样式
    CSS去除input和textarea点击选中框
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12730829.html
Copyright © 2011-2022 走看看