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

相关推荐
threerocks5 小时前
Jev 入门第一课
算法
西柚研究生1234566 小时前
论文分析17:YOLOv11_UAVNet:无人机航拍图像专用目标检测算法
人工智能·python·深度学习·算法·目标检测
hetao17338377 小时前
2026-09-17 hetao1733837 的刷题记录
c++·算法
午彦琳8 小时前
2026.9.17
数据结构·算法·leetcode
木井巳8 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
怕浪猫9 小时前
从 Windows 换到 Mac 三个月,我真香了
算法·面试·架构
aichitang202410 小时前
前端小skill
前端·人工智能·算法·ai·前端框架
All for pursuit.11 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
木子算法11 小时前
测出来的值会抖:约束和目标带噪声时,「可行」和「更好」该怎么判
人工智能·算法·目标跟踪
hanlin0312 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode