当前位置: 首页 > article >正文

力扣刷题39. 组合总和

39. 组合总和 - 力扣(LeetCode)

需要定义一个index变量用来记录访问数组的下标,每次递归进行传参,在搜索过程中,因为为了避免重复数据,而且允许一个元素的重复出现,传入index时传入当前遍历的i值即可

class Solution {
    List<List<Integer>> list;
    List<Integer> res;
    int target;
    int count;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        this.target = target;
        list = new ArrayList<>();
        res = new ArrayList<>();
        count = 0;
        dfs(candidates,0);
        return list;
    }
     public void dfs(int[] candidates,int index) {
        if (count == target) {
            list.add(new ArrayList<>(res));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (count + candidates[i] <= target) {
                res.add(candidates[i]);
                count += candidates[i];
                dfs(candidates,i);
                //回溯
                count -=  candidates[i];
                res.remove(res.size() - 1);
            }
        }
    }
}


http://www.kler.cn/a/601163.html

相关文章:

  • github怎么关闭issue禁止评论设置步骤
  • [ChatGPT 高级进阶系列] 用ChatGPT加速前端开发:高级思维链提示全解析
  • 【漫话机器学习系列】161.验证曲线(Validation Curve)
  • 括号合法题
  • 在CentOS系统上运行Ruby on Rails应用的详细步骤
  • 借助可视化,快速洞察数据背后的商机
  • 游戏如何检测GG修改器
  • 英伟达「虚拟轨道+AI调度」专利:开启自动驾驶3.0时代的隐形革命
  • 表单查询、多表查询
  • 3.24前端模拟面试
  • 如何下载 Postman?快速指南!
  • Java 基于微信小程序的开放实验室预约管理系统
  • 诡异的服务重启原因探索
  • (基本常识)C++中const与引用——面试常问
  • 电机倍频曲线的一些奇异特性-原因分析及应用
  • 气膜科技,突破极限:高海拔施工的全新解决方案—轻空间
  • 数据结构每日一题day2(顺序表)★★★★★
  • 一个简单的用C#实现的分布式雪花ID算法
  • Apache Tomcat RCE漏洞(CVE-2025-24813)
  • python 格式化利器