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

相关推荐
Omics Pro几秒前
强生:以机理为中心!虚拟细胞世界模型
数据库·人工智能·python·深度学习·算法·机器学习·自然语言处理
FPGA信号处理12 分钟前
【凸优化】第一节课(下):保凸运算、分离超平面与 Farkas 引理
人工智能·算法·机器学习
怕浪猫28 分钟前
Agent 的记忆系统怎么设计?面试官想听的是这个
算法·面试·github
C++ 老炮儿的技术栈32 分钟前
C++ const 的3个核心作用
服务器·c语言·c++·算法·c
有毒的教程1 小时前
Dev-C++ 避免爆栈(Stack Overflow)完整方案
c++·算法·深度优先
在所不辞兄1 小时前
刚性问题误差容限设置技巧
深度学习·神经网络·算法·机器学习
啊啊啊啊啊!!!!1 小时前
unordered_map和unordered_set的使用
算法
java_nnnn1 小时前
LeetCode刷题双指针(快乐数+盛最多水的容器)Java
算法·leetcode·职场和发展
yi01110 小时前
LeetCode 219:存在重复元素 II——哈希表记录“最近一次出现的位置”
数据结构·人工智能·笔记·python·算法·leetcode·哈希表
灯澜忆梦13 小时前
【面向对象编程C++】| 基础语法
java·c++·算法