【算法三十四】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 小时前
【机械设计】磁粉检测机器人的设计与验证
算法·机器人
Navigator_Z6 小时前
LeetCode //C - 1220. Count Vowels Permutation
c语言·算法·leetcode
吃好睡好便好6 小时前
判断函数的使用
学习·算法·matlab·生活·判断函数
2601_956121976 小时前
线性DP(入门)
c++·算法·动态规划
feilieren6 小时前
leetcode - 389. 找不同
算法·leetcode
挽星安6 小时前
2026/8/29
数据结构·算法
positive_zpc6 小时前
进阶数据结构图——最短路径(二)
数据结构·算法·图论·最短路径
positive_zpc7 小时前
进阶数据结构图——最小生成树(一)
数据结构·算法·图论
码完就睡7 小时前
数据结构——遍历二叉树
数据结构·算法
evans在进步7 小时前
LeetCode 238 除自身以外数组的乘积:前缀积与后缀积详解
算法·leetcode·职场和发展