LeetCode.39 组合总和

本文提供了一种解决LeetCode上组合总和问题的方法。通过深度优先搜索(DFS)实现,代码中详细展示了如何寻找所有可能的数字组合以达到目标值,并通过剪枝策略减少不必要的搜索。

原题:

https://leetcode-cn.com/problems/combination-sum/
在这里插入图片描述
题解

package com.leetcode.code;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName Code39
 * @Author ZK
 * @Description
 * @Date 2021/1/25 11:21
 * @Version 1.0
 **/
public class Code39 {

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

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        int len = candidates.length;
        if (len == 0) {
            return res;
        }
//        排序,对应剪枝
        Arrays.sort(candidates);

        dfs(candidates, 0, len, target, new ArrayList<Integer>(), res);

        return res;
    }

    private static void dfs(int[] candidates, int begin, int len, int target, List<Integer> path, List<List<Integer>> res){
        if (target == 0) {
            res.add(new ArrayList<Integer>(path));
            return;
        }
//        i=begin,为了是去掉重复数据,如果i=0的话,则是全部的解
        for (int i = begin; i < len; i++) {
            int cur = candidates[i];
//            剪枝,对应排序,如果加上当前数值已经小于0之后,后边的数据则不用继续递归,剪掉
            if (target - cur < 0) {
                break;
            }
            path.add(cur);
            dfs(candidates, i, len, target-cur, path, res);
//            回溯,移出当前数据
            path.remove(path.size()-1);
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

难过的风景

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

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

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

打赏作者

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

抵扣说明:

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

余额充值