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
  • 相关阅读:
    C# 特性学习笔记
    Nhibernate学习的第二天
    Nhibernate学习的第一天
    SQL循环添加表中的字段
    加班
    bat文件重启SQL服务和IIS服务
    判断是不是手机访问的网站
    解决Ueditor 不兼容IE7 和IE8
    实现链表的初始化,按值查找,插入,删除
    判断任一二叉树,是否为满二叉树.(输出二叉树,节点总数,二叉树深度)
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12730829.html
Copyright © 2011-2022 走看看