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

相关推荐
小糯米6012 小时前
C++ 并查集
java·c++·算法
重庆小透明2 小时前
力扣刷题【3】相交链表
算法·leetcode·链表
算法鑫探2 小时前
C语言实战:学生成绩统计与分析
c语言·数据结构·算法·新人首发
IAUTOMOBILE2 小时前
Code Marathon 项目源码解析与技术实践
java·前端·算法
Lyyaoo.2 小时前
【JAVA基础面经】深拷贝与浅拷贝
java·开发语言·算法
x_xbx2 小时前
LeetCode:202. 快乐数
算法·leetcode·职场和发展
老虎06272 小时前
LeetCode热题100 刷题笔记(第四天)二分 「 寻找两个正序数组的中位数」
笔记·算法·leetcode
_日拱一卒2 小时前
LeetCode:最小覆盖字串
java·数据结构·算法·leetcode·职场和发展
小O的算法实验室2 小时前
2026年IEEE TEVC,面向农业多机器人任务分配的自适应多目标任务划分算法,深度解析+性能实测
算法·机器人·论文复现·智能算法·智能算法改进