dfs+剪枝,LeetCode 39. 组合总和

一、题目

1、题目描述

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

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

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

2、接口描述

python3
复制代码
python 复制代码
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
cpp
复制代码
cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        
    }
};

3、原题链接

39. 组合总和


二、解题报告

1、思路分析

考虑暴力dfs,选多个或不选,当前枚举到 i ,还差res数值

复制代码
            dfs(i - 1, res)

            path.append(candidates[i])
            dfs(i, res - candidates[i])
            path.pop()

显然可以剪枝,res 小于0的时候剪掉(可行性剪枝)

进一步,我们优化搜索顺序,从小到大枚举

当res < candidate[i]时,往后枚举不能满足,也可以剪枝(优化搜索顺序剪枝)

这样这道题其实就蛮快了

但是如果数据量更大呢?

搜索树的起点终点已知,可以双向广搜,能够有效降低复杂度

但是我们发现每个结点都相当于一个完全背包的状态

换言之,我们预处理完全背包,就可以使得搜索顺序朝着可行路径去走

所以采用预排序和预处理完全背包来进行剪枝:

优化搜索顺序 & 可行性剪枝

2、复杂度

时间复杂度: 不会算 空间复杂度:O(n target)

3、代码详解

python3
复制代码
python 复制代码
class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        n = len(candidates)
        candidates.sort()
        f = [[False] * (target + 1) for _ in range(n + 1)]
        f[0][0] = True
        for i, x in enumerate(candidates):
            for j in range(target + 1):
                f[i + 1][j] = f[i][j] or j >= x and f[i + 1][j - x]
        
        ret = []
        path = []
        def dfs(i: int, res: int):
            if not res:
                ret.append(path.copy())
                return
            
            if res < 0 or not f[i + 1][res]:
                return
            
            dfs(i - 1, res)

            path.append(candidates[i])
            dfs(i, res - candidates[i])
            path.pop()

        dfs(n - 1, target)

        return ret
        
cpp
复制代码
cpp 复制代码
class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> ret;
        vector<int> path;
        int n = candidates.size();
        sort(candidates.begin(), candidates.end());
        vector<vector<bool>> f(n + 1, vector<bool>(target + 1));
        f[0][0] = 1;
        for(int i = 0; i < n; i++)
            for(int j = 0; j <= target; j++)
                f[i + 1][j] = f[i][j] || (j >= candidates[i] && f[i + 1][j - candidates[i]]);
        function<void(int, int)> dfs = [&](int i, int res){
            if(!res) {
                ret.emplace_back(path);
                return;
            }
            if(res < 0 || !f[i + 1][res]) return;
            dfs(i - 1, res);

            path.emplace_back(candidates[i]);
            dfs(i, res - candidates[i]);
            path.pop_back();
        };
        dfs(n - 1, target);
        return ret;
    }
};
相关推荐
小O的算法实验室1 小时前
2025年IEEE TETCI,异构无人机取送货问题中的转运优化,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
chao1898448 小时前
基于 SPEA2 的多目标优化算法 MATLAB 实现
开发语言·算法·matlab
沪漂阿龙8 小时前
AI大模型面试题:支持向量机是什么?间隔最大化、软间隔、核函数、LinearSVC 全面拆解
人工智能·算法·支持向量机
little~钰8 小时前
倍增算法和ST表
算法
知识领航员9 小时前
蘑兔AI音乐深度实测:功能拆解、实测表现与适用场景
java·c语言·c++·人工智能·python·算法·github
薛定e的猫咪9 小时前
因果推理研究方向综述笔记
人工智能·笔记·深度学习·算法
如何原谅奋力过但无声10 小时前
【灵神高频面试题合集06-08】反转链表、快慢指针(环形链表/重排链表)、前后指针(删除链表/链表去重)
数据结构·python·算法·leetcode·链表
平行侠10 小时前
037插入排序 - 整理扑克牌的算法
数据结构·算法
ECT-OS-JiuHuaShan11 小时前
彻底定理化:从量子纠缠到量子代谢
数据库·人工智能·学习·算法·生活·量子计算