LeetCode 0039.组合总和:回溯 + 剪枝

【LetMeFly】39.组合总和:回溯 + 剪枝

力扣题目链接:https://leetcode.cn/problems/combination-sum/

给你一个 无重复元素 的整数数组 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(target, index),用来处理距离目标还剩target,处理过候选数组的[0, index)的情况。

为了实现这个函数,我们还需要两个"全局"变量(或者通过参数传递):ans用来存放所有可行的情况(答案)、now用来存放当前已选元素。

函数dfs终止条件:

  • target为0:now为一种可选方案,now加入ans数组并终止递归
  • index超出候选数组的下标范围:递归终止

函数dfs要做的事:

  1. 在已选方案now的基础上,不选 当前元素candidates[index]:递归dfs(target, index + 1)
  2. 在已选方案now的基础上,选择 当前元素candidates[index]:将candidates[index]加入now数组,递归dfs(target - candidates[index], index),(回溯)将candidates[index]now数组中剔除

剪枝方案:target - candidates[index] >= 0时再递归回溯。

  • 时间复杂度 O ( S i z e ( a n s ) ) O(Size(ans)) O(Size(ans))
  • 空间复杂度 O ( t a r g e t ) O(target) O(target):空间复杂度为递归深度,最坏情况下全是1要递归target

AC代码

C++
cpp 复制代码
class Solution {
private:
    vector<vector<int>> ans;
    vector<int> now;

    void dfs(vector<int>& candidates, int target, int index) {
        if (!target) {
            ans.push_back(now);
            return;
        }
        if (index == candidates.size()) {
            return;
        }
        // not choose
        dfs(candidates, target, index + 1);
        // choose
        if (target - candidates[index] >= 0) {
            now.push_back(candidates[index]);
            dfs(candidates, target - candidates[index], index);  // 这里不能是index + 1,因为可以重复选择
            now.pop_back();
        }
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(candidates, target, 0);
        return ans;
    }
};
Python
python 复制代码
# from typing import List

class Solution:
    def dfs(self, target: int, index: int) -> None:
        if not target:
            self.ans.append(self.now[:])
            return
        if index == len(self.candidates):
            return
        # not choose
        self.dfs(target, index + 1)
        # choose
        if target >= self.candidates[index]:
            self.now.append(self.candidates[index])
            self.dfs(target - self.candidates[index], index)
            self.now.pop()        

    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        self.ans = []
        self.now = []
        self.candidates = candidates
        self.dfs(target, 0)
        return self.ans

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/137994260

相关推荐
利刃大大19 分钟前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
Joyner20183 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展
因兹菜3 小时前
[LeetCode]day9 203.移除链表元素
算法·leetcode·链表
LNsupermali3 小时前
力扣257. 二叉树的所有路径(遍历思想解决)
算法·leetcode·职场和发展
雾月553 小时前
LeetCode LCR180文件组合
算法·leetcode·职场和发展
萌の鱼3 小时前
leetcode 2080. 区间内查询数字的频率
数据结构·c++·算法·leetcode
Tisfy3 小时前
LeetCode 0541.反转字符串 II:模拟
算法·leetcode·字符串·题解
labmem15 小时前
Leetcode:541
算法·leetcode·职场和发展
某个默默无闻奋斗的人6 小时前
深度优先搜索(DFS)
算法·深度优先
圆圆滚滚小企鹅。6 小时前
刷题记录 HOT100回溯算法-6:79. 单词搜索
笔记·python·算法·leetcode