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
  • 相关阅读:
    单例模式的double check写法中的volatile关键字
    java开发中避免NullPointerException
    java.lang.NoClassDefFoundError: javax/xml/bind/JAXBContext
    linux环境工作记录
    常用Java开发者工具
    compile once,run anywhere
    Java 线程
    常用的git命令
    oracle 随笔
    常用px,pt,em换算表
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12730829.html
Copyright © 2011-2022 走看看