【算法三十四】39. 组合总和

39. 组合总和 - 力扣(LeetCode)

回溯:

java 复制代码
class Solution {
    public List<List<Integer>> combinationSum(int[] candidates,int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> combine = new ArrayList<>();
        dfs(candidates,target,ans,combine,0);
        return ans;
    }
    
    private void dfs(int[] candidates, int target,List<List<Integer>> ans,List<Integer> combine,int index){
        if(index == candidates.length){
            return;
        }
        
        if(target == 0){
            //记得要用new
            ans.add(new ArrayList<>(combine));
            return;
        }
        //往深处找
        dfs(candidates,target,ans,combine,index+1);
        
        if(target-candidates[index]>=0){
            combine.add(candidates[index]);
            //看看可不可以重复选
            dfs(candidates,target-candidates[index],ans,combine,index);
            //动态数组长度是size()
            combine.remove(combine.size()-1);
        }
    }
}

时间复杂度:O(S) S 为所有可行解的长度之和

空间复杂度:O(target/min) 递归栈的深度

相关推荐
星星码️20 小时前
LeetCode刷题简单篇之反转字母
c++·算法·leetcode
naturerun20 小时前
螺旋形遍历奇数阶矩阵
c++·算法·矩阵
wuweijianlove21 小时前
算法复杂度的实验估算与误差分布建模的技术7
算法
佳xuan21 小时前
简而言之c++
c++·算法
变量未定义~21 小时前
星际争霸、宝石塔的亮度差异、寻找食物储量
算法
YL2004042621 小时前
027合并两个有序链表
java·数据结构·算法·链表
MATLAB代码顾问1 天前
【智能优化】无穷优化算法(INFO)原理与Python实现
开发语言·python·算法
炽烈小老头1 天前
【每天学习一点算法 2026/05/10】合并K个排序链表
学习·算法·链表
SilentSamsara1 天前
迭代器协议:`__iter__` / `__next__` 的完整执行流程
开发语言·人工智能·python·算法·机器学习
AI科技星1 天前
算法联盟ROOT · 全域数学物理卷第20、21、22分册:量子纠缠、隐形场论与时间膨胀
人工智能·算法·数学建模·数据挖掘·机器人