zoukankan      html  css  js  c++  java
  • leetcode刷题-39组合总和

    题目

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

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

    思路

    这道题采用遍历的方式效率太低,因此可以想到回溯的方式。

    算法:

    1.对candidates进行排序

    2.回溯函数combination:索引i,当前数组tmp,下一目标target:

      2.1 当target == 0时,满足条件,tmp添加进入result

      2.2 剪枝 当索引等于candidates长度的时候,已经结束,return;当target < candidates[i]的时候,后续也不存在满足的结果,因此剪枝,return。

      2.3 重复调用自身

      2.4 调用下一个元素

    实现

    class Solution:
        def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
            if(not candidates):
                return []
            n=len(candidates)
            result=[]
            candidates.sort()
    
            def combination(idx, tmp, target):
                if target == 0 :
                    result.append(tmp)
                    return
                if idx == n or target < candidates[idx]:
                    return
                combination(idx, tmp+[candidates[idx]],target-candidates[idx])
                combination(idx+1, tmp, target)
    
            combination(0,[],target)
            return result
  • 相关阅读:
    第5周作业
    第四周JAVA作业
    第三周JAVA学习
    第二周JAVA学习日志
    有关JAVA学习
    Swift 页面跳转
    Swift 登录判断
    单元测试学习
    WCF学习心得
    初次使用Oracle
  • 原文地址:https://www.cnblogs.com/mgdzy/p/13418903.html
Copyright © 2011-2022 走看看