39. 组合总和

本文详细解析了LeetCode第39题“组合总和”的解决方案,通过回溯法实现,提供了完整的Java代码示例,包括如何使用List进行元素的添加、移除以及回溯过程中的剪枝策略。

题目:

39. 组合总和
在这里插入图片描述

题解:回溯法

在这里插入图片描述

代码:回溯法

import java.util.*;

public class code39 {

    public static int sum = 0;

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(res, list, target, candidates, 0);
        return res;
    }

    public static void backtrack(List<List<Integer>> res, List<Integer> list, int target, int candidates[], int start) {
        if (sum == target) {
            res.add(new ArrayList<>(list));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            if (sum + candidates[i] <= target) {
                list.add(candidates[i]);
                sum += candidates[i];
                backtrack(res, list, target, candidates, i);
                sum -= candidates[i];
                list.remove(list.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        int[] candidates1 = { 2, 3, 6, 7 };
        int target1 = 7;
        List<List<Integer>> combinationSum1 = combinationSum(candidates1, target1);
        System.out.println(combinationSum1);

        int[] candidates2 = { 2, 3, 5 };
        int target2 = 8;
        List<List<Integer>> combinationSum2 = combinationSum(candidates2, target2);
        System.out.println(combinationSum2);
    }
}

参考:

  1. 学一套走天下(回溯算法)
  2. 回溯算法 + 剪枝(Python 代码、Java 代码)
  3. Leetcode 39:组合总和(最详细的解法!!!)
  4. Leetcode学习笔记-39-组合总和
  5. 39. 组合总和
  6. leetcode 回溯法 模板
  7. 递归,回溯,DFS,BFS的理解和模板
  8. 递归,回溯,DFS,BFS的理解和模板
  9. Java中List的remove方法
  10. Java list.remove( )方法需要注意的两个地方
  11. ArrayList的remove()方法
  12. List 初始化
  13. 全面解析回溯法:算法框架与问题求解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dev_zyx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值