LeetCode Python - 39.组合总和

目录


题目

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7

输出:[[2,2,3],[7]]

解释:

2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。

7 也是一个候选, 7 = 7 。

仅有这两种组合。

示例 2:

输入: candidates = [2,3,5], target = 8

输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1

输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

答案

排序 + 剪枝 + 回溯(两种写法)

我们可以先对数组进行排序,方便剪枝。

接下来,我们设计一个函数 dfs(i,s),表示从下标 i 开始搜索,且剩余目标值为 s,其中 i 和 s 都是非负整数,当前搜索路径为 t,答案为 ans。

在函数 dfs(i,s) 中,我们先判断 s 是否为 0,如果是,则将当前搜索路径 t 加入答案 ans 中,然后返回。如果 s<candidates[i],说明当前下标及后面的下标的元素都大于剩余目标值 s,路径不合法,直接返回。否则,我们从下标 i 开始搜索,搜索的下标范围是 j∈[i,n),其中 n 为数组 candidates 的长度。在搜索的过程中,我们将当前下标的元素加入搜索路径 t,递归调用函数 dfs(j,s−candidates[j]),递归结束后,将当前下标的元素从搜索路径 t 中移除。

我们也可以将函数 dfs(i,s) 的实现逻辑改为另一种写法。在函数 dfs(i,s) 中,我们先判断 s 是否为 0,如果是,则将当前搜索路径

t 加入答案 ans 中,然后返回。如果 i≥n 或者 s<candidates[i],路径不合法,直接返回。否则,我们考虑两种情况,一种是不选当前下标的元素,即递归调用函数 dfs(i+1,s),另一种是选当前下标的元素,即递归调用函数 dfs(i,s−candidates[i])。

在主函数中,我们只要调用函数 dfs(0,target),即可得到答案。

时间复杂度 O(2 n ×n),空间复杂度 O(n)。其中 n 为数组

candidates 的长度。由于剪枝,实际的时间复杂度要远小于

O(2 n ×n)。

python 复制代码
class Solution(object):
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """

        def dfs(i, s):
            if s == 0:
                ans.append(t[:])
                return
            if s < candidates[i]:
                return
            for j in range(i, len(candidates)):
                t.append(candidates[j])
                dfs(j, s - candidates[j])
                t.pop()

        candidates.sort()
        t = []
        ans = []
        dfs(0, target)
        return ans
python 复制代码

运行结果

相关推荐
2401_828890647 分钟前
使用 BERT 实现意图理解和实体识别
人工智能·python·自然语言处理·bert·transformer
多恩Stone1 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
xiaopengbc1 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@2 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.2 小时前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
偷心伊普西隆2 小时前
Python EXCEL 理论探究:格式转换时处理缺失值方法
python·excel
精灵vector3 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain
1白天的黑夜13 小时前
哈希表-49.字母异位词分组-力扣(LeetCode)
c++·leetcode·哈希表