【算法三十四】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) 递归栈的深度

相关推荐
是main不是漫5 小时前
【快慢指针 | LeetCode202 快乐数】鸽巢原理佐证环特性,快慢指针巧解快乐数
c语言·开发语言·c++·算法
Felven5 小时前
A. Iskander and Drawings
算法
qq_348231859 小时前
大模型算法: 反向传播
算法
电科_银尘9 小时前
【大模型算法与工程 27】训练配方:批量、学习率、精度与梯度裁剪
学习·算法·机器学习
专注仿真10 小时前
智能体训练之模仿学习:GAIL 算法详解与实战
python·算法·仿真·多智能体强化学习·afsim智能体训练
leobertlan12 小时前
痛苦系列 | DSP-04 截断时空的“窗”:FIR 滤波器设计与线性相位
算法
秋天的怀念_David13 小时前
算法一千零一夜 · 第三十五夜 · 恢复风暴
java·程序人生·算法
泯泷15 小时前
别再“裸聊”大模型了!你家的 AI 为什么总胡说八道?根子在 RAG
人工智能·算法·架构
2601_9679801116 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块