代码随想录——组合总和(Leetcode LCR81)

题目链接
在这里插入图片描述

回溯

class Solution {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    List<Integer> list = new ArrayList<Integer>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtracking(candidates, target, 0, 0);
        return res;
    }
    public void backtracking(int[] candidates, int target, int sum, int startIndex){
        if(sum > target){
            return;
        }
        if(sum == target){
            res.add(new ArrayList<>(list));
            return;
        }
        for(int i = startIndex; i < candidates.length; i++){
            sum += candidates[i];
            list.add(candidates[i]);
            // 数字可以无限制重复被选取,所以i不用+1
            backtracking(candidates, target, sum, i);
            sum -= candidates[i];
            list.removeLast();
        }
    }
}

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-18 15:16:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-18 15:16:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-18 15:16:02       87 阅读
  4. Python语言-面向对象

    2024-06-18 15:16:02       96 阅读

热门阅读

  1. Mysql中常用的sql语句(适合萌新学习)

    2024-06-18 15:16:02       35 阅读
  2. 函数参数调用 4.0

    2024-06-18 15:16:02       34 阅读
  3. CLIP模型调用的一段代码及解释

    2024-06-18 15:16:02       31 阅读