zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第40题:给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。

    题目:

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

    candidates 中的每个数字在每个组合中只能使用一次。

    说明:

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

    思路:总体思路和第39题一样,但是在每个数字只能使用一次的条件下,需要进行第二次剪枝。

    程序:

    class Solution:
        def combinationSum2(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
                for temp_index in range(index, length):
                    if temp_index > index and candidates[temp_index] == candidates[temp_index - 1]:
                        continue
                    auxiliary(temp_index + 1, temp_result + [candidates[temp_index]], target - candidates[temp_index])
            auxiliary(0, temp_result, target)
            return result
  • 相关阅读:
    linux下yum错误:[Errno 14] problem making ssl connection Trying other mirror.
    linux下sudo命令
    myeclipse修改编译器版本的方法 .
    java 使用POI读写Excel文件(兼容2003、2007)
    Google.ProtocolBuffers.dll 之.Net应用(一)
    禁止Grid、TreeGrid列排序和列菜单
    在VS2008中加入ExtJS智能提示
    教程地址
    ExtJS xtype 一览
    ExtJS中,将Grid表头中的全选复选框取消复选
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12731333.html
Copyright © 2011-2022 走看看