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

相关推荐
三毛的二哥5 小时前
BEV:典型BEV算法总结
人工智能·算法·计算机视觉·3d
南宫萧幕6 小时前
自控PID+MATLAB仿真+混动P0/P1/P2/P3/P4构型
算法·机器学习·matlab·simulink·控制·pid
故事和你917 小时前
洛谷-数据结构1-4-图的基本应用1
开发语言·数据结构·算法·深度优先·动态规划·图论
我叫黑大帅7 小时前
为什么map查找时间复杂度是O(1)?
后端·算法·面试
炽烈小老头8 小时前
【每天学习一点算法 2026/04/20】除自身以外数组的乘积
学习·算法
skilllite作者8 小时前
AI agent 的 Assistant Auto LLM Routing 规划的思考
网络·人工智能·算法·rust·openclaw·agentskills
py有趣10 小时前
力扣热门100题之不同路径
算法·leetcode
_日拱一卒10 小时前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
啊哦呃咦唔鱼10 小时前
LeetCodehot100-394 字符串解码
算法
小欣加油10 小时前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展