LeetCode:39. 组合总和

跟着carl学算法,本系列博客仅做个人记录,建议大家都去看carl本人的博客,写的真的很好的!
代码随想录
LeetCode:39. 组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7

输出:[[2,2,3],[7]]

解释:

2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。

7 也是一个候选, 7 = 7 。

仅有这两种组合。

示例 2:

输入: candidates = [2,3,5], target = 8

输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1

输出: []

本题里面candidates是可以重复的,在进入递归函数的时候传递的参数是i,上一题不能重复,传递的是i+1

java 复制代码
	public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        backtracking(candidates, target, 0, 0, new ArrayList<>(), res);
        return res;
    }

    private void backtracking(int[] candidates, int target, int index, int sum, List<Integer> path,
            List<List<Integer>> res) {
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            if (sum + candidates[i] > target)
                break;
            path.add(candidates[i]);
            // 注意因为数字可以重复,所以递归函数中传递的还是i
            backtracking(candidates, target, i, sum + candidates[i], path, res);
            path.removeLast();
        }
    }
相关推荐
zzb15801 天前
RAG from Scratch-优化-query
java·数据库·人工智能·后端·spring·mybatis
wuqingshun3141591 天前
如何停止一个正在退出的线程
java·开发语言·jvm
卷福同学1 天前
QClaw内测体验,能用微信指挥AI干活了
人工智能·算法·ai编程
sali-tec1 天前
C# 基于OpenCv的视觉工作流-章34-投影向量
图像处理·人工智能·opencv·算法·计算机视觉
xiaoye-duck1 天前
《算法题讲解指南:递归,搜索与回溯算法--递归》--3.反转链表,4.两两交换链表中的节点,5.快速幂
数据结构·c++·算法·递归
Eward-an1 天前
【算法竞赛/大厂面试】盛最多水容器的最大面积解析
python·算法·leetcode·面试·职场和发展
山栀shanzhi1 天前
归并排序(Merge Sort)原理与实现
数据结构·c++·算法·排序算法
阿豪学编程1 天前
LeetCode438: 字符串中所有字母异位词
算法·leetcode
Trouvaille ~1 天前
【递归、搜索与回溯】专题(七):FloodFill 算法——勇往直前的洪水灌溉
c++·算法·leetcode·青少年编程·面试·蓝桥杯·递归搜索回溯
地平线开发者1 天前
征程 6P codec decoder sample
算法·自动驾驶