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 复制代码

运行结果

相关推荐
满怀101542 分钟前
【Flask全栈开发指南】从零构建企业级Web应用
前端·python·flask·后端开发·全栈开发
PWRJOY42 分钟前
Flask-SQLAlchemy_数据库配置
数据库·python·flask
mahuifa1 小时前
Qt图表绘制(QtCharts)- 性能优化(13)
python·qt·pyside6·开发经验·qtchart
Bugabooo1 小时前
python打卡DAY22
开发语言·python
低维歌者2 小时前
python训练营day27
java·开发语言·python
微刻时光2 小时前
影刀处理 Excel:智能工具带来的高效变革
人工智能·python·低代码·自动化·excel·rpa·影刀rpa
大帅不是我2 小时前
Python多进程编程执行任务
java·前端·python
Fu_lucas2 小时前
Python Logging 模块完全指南
开发语言·python
Eiceblue2 小时前
Python 在Excel单元格中应用多种字体样式
开发语言·vscode·python·pycharm·excel
Superstarimage4 小时前
使用conda创建python虚拟环境,并自定义路径
windows·python·conda