leetcode:组合总和(java回溯)

回溯算法实战:LeetCode 216组合总和III的Java解法与剪枝优化 回溯算法是解决组合优化问题的经典深度优先搜索技术,其核心原理是通过系统性的尝试与回退机制遍历所有可能的解空间。在算法设计与性能优化中,剪枝策略能够显著减少不必要的计算路径,提升执行效率。对于LeetCode等编程练习平台上的组合总和问题,理解回溯模板的应用与剪枝优化技巧具有重要的实践价值。本文以组合总和III为例,深入解析如何通过Java实现高效的回溯解法,涵盖参数设计、终止条件判断以及基于剩余数字数量的剪枝优化,帮助开发者掌握这一在技术面试和工程实践中广泛应用的核心算法思想。 阅读详情
package LeetCode;

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

/*
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]
 */
public class CombinationSum {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> resluts = new ArrayList<>();
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        combinationSumhuisu(candidates, target, resluts,0,result);
        return result;
    }

    public static void combinationSumhuisu(int[] candidates, int target, List<Integer> results,int start,List<List<Integer>> result) {

            //判断是否可以整减
            if(target<0){
                return ;
            }else  if (target == 0) {
                //指向一块新的不变的地址否则result会随着results改变而改变
                result.add(new ArrayList<Integer>(results));
                return;
            } else
                //start防止了i=2然后递归后i=1重复i=1 递归i=2时所以要固定其i
                for (int i = start; i < candidates.length; i++) {
                //判断target是否可以减掉candidates
                    results.add(candidates[i]);
                    combinationSumhuisu(candidates, target-candidates[i], results,i,result);
                    results.remove(results.size()-1);
        }
    }

    public static void main(String[] args) {
        int[] a = {2, 3, 6, 7};
        int tage = 7;
        CombinationSum b = new CombinationSum();
        System.out.println(b.combinationSum(a, tage));
    }
}

 

相关推荐

手把手移植st7701s驱动:MT6763+安卓8.0屏幕适配保姆级教程

本文详细介绍了在MT6763平台上移植ST7701S驱动的完整流程,涵盖从LK层到Kernel层的适配方案,特别针对安卓8.0系统的特殊要求。通过MIPI转RGB屏幕适配的实战教程,帮助开发者解决常见显示问题,包括无显示、色彩异常和屏幕错位等,并提供高级调试技巧如彩条测试模式和闪屏解决方案。

weixin_29186249的博客 159

java实现组合总和

LeetCode算法题39

weixin_61876893的博客 470

AI工程化之生成式UI & A2UI(二)

本文介绍了生成式UI框架A2UI的架构设计与核心实现。项目采用AI协作开发模式,通过ATDD(AI驱动的测试驱动开发)确保代码质量。前端SDK基于zustand实现框架无关的状态管理,包含协议解析器、存储管理、渲染器等核心模块。重点展示了基础store构建、A2UI协议解析器的实现过程,包括mock数据准备、测试用例生成和可视化调试。项目采用monorepo管理,利用vite实现高效开发构建。整个系统设计遵循模块化原则,通过清晰的接口定义实现各组件解耦,为后续功能扩展打下基础。

qq_34306228的博客 407

【算法-Java实现】组合总和

【算法-Java实现】组合总和 一.问题描述: 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。candidates 中的数字可以无限制重复被选取。 比如: 输入:[2,3,6,7];输出:[[7], [2, 2, 3]] 输入:[3,4,5,6,7,8,9];输出:[[8], [4, 4], [3, 5]] 本题来源:力扣39 二.问题解答: 思路:搜索回溯 递归函数结构体: dfs(int[] cand

HKD的博客 2024

Electron多窗口开发避坑指南:Pinia状态同步的3种解决方案对比

本文深入探讨了在Electron多窗口应用中实现Pinia状态同步的三种核心方案。针对Electron多窗口架构下状态隔离的挑战,文章对比了基础事件通信、共享存储以及智能Pinia插件等方案的优劣与适用场景,并提供了生产级的实现指南与选型建议,帮助开发者构建健壮高效的桌面应用。

spice的博客 479

TwinCAT3实战:从零搭建倍福PLC的Modbus-TCP Server

本文详细介绍了如何使用TwinCAT3从零搭建倍福PLC的Modbus-TCP Server,包括环境准备、工程配置、参数设置、客户端连接测试及常见问题排查。通过实战步骤和实用技巧,帮助工程师快速掌握倍福PLC与Modbus-TCP的通信实现,提升工业自动化项目的开发效率。

weixin_30797199的博客 174

力扣:组合总和java

力扣:组合总和java

qq_42325147的博客 415

深度学习图神经网络 (GNN) —— 处理图结构数据(六十九)

本文系统介绍了图神经网络(GNN)的核心概念、主流模型及其应用。主要内容包括: GNN基础:阐述了图结构数据的特性(节点数不定、连接不规则),以及GNN相比CNN/RNN的优势在于处理非欧式空间的图数据。 核心机制:重点讲解了消息传递框架(MPNN),通过聚合邻居信息迭代更新节点表示,并分析了GCN的归一化邻接矩阵计算和GAT的注意力权重机制。 典型模型: GCN:基于归一化邻接矩阵的特征传播 GAT:引入注意力机制区分邻居重要性 GraphSAGE:通过采样解决大图扩展性问题 GIN:理论表达能力最强的图

hello.reader 302

Leetcode 组合总和

该算法的复杂度取决于输入数组candidates的大小以及目标值target。由于每个数字可以被多次使用,回溯算法会生成大量可能的组合,然后通过递归逐一验证。这种方法虽然可能会有较高的时间复杂度,但可以保证找到所有合法的组合。return;return;++i) {//添加当前元素//删除当前元素//按照下标移除元素。

985小菜鸡 1425

数学建模学习(121):Python实现模糊AHP(Fuzzy AHP)——从原理到实践

Python实现模糊AHP(Fuzzy AHP)

全栈川川 1542

Python爬虫模拟登录京东并抓取商品数据

京东是一个拥有海量商品数据的电子商务平台。作为爬虫开发者,能够抓取这些数据将为我们提供很多机会进行数据分析、价格预测、市场调研等工作。然而,京东的反爬虫机制非常强大,包括但不限于验证码、动态加载页面、IP封禁等。因此,想要通过Python爬虫抓取京东的数据并不容易。在本文中,我们将从分析京东的登录机制开始,逐步介绍如何使用Python中的各种工具,如。

2201_76125261的博客 1831

java组合总和(力扣Leetcode39)

解释:2 和 3 可以形成一组候选,2 + 2 + 3 = 7。7 也是一个候选, 7 = 7。我们需要在给定的数字数组中寻找所有可能的组合,使其和等于目标数。输入:candidates = [2,3,6,7], target = 7。输入: candidates = [2,3,5], target = 8。的所有不同组合,并以列表形式返回。输入: candidates = [2], target = 1。输出: [[2,2,2,2],[2,3,3],[3,5]]输出:[[2,2,3],[7]]

m0_73065928的博客 628

爬虫:一文掌握 Pydoll 的详细使用(彻底改变浏览器自动化,且能绕过绕过验证码!)

Pydoll正在彻底改变浏览器自动化!与其他解决方案不同,它消除了对Web驱动程序的需求,提供了流畅可靠的自动化体验和本机异步性能。

数据知道的博客 1万+

《LeetCode力扣练习》代码随想录——回溯算法(组合总和---Java)

《LeetCode力扣练习》代码随想录——回溯算法(组合总和---Java)

XRT_knives的博客 438

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

《LeetCode力扣练习》代码随想录——回溯算法(组合总和II---Java)

《LeetCode力扣练习》代码随想录——回溯算法(组合总和II---Java)

XRT_knives的博客 413

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

《LeetCode力扣练习》代码随想录——回溯算法(组合总和III---Java)

《LeetCode力扣练习》代码随想录——回溯算法(组合总和III---Java)

XRT_knives的博客 429

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

leetcode39. 组合总和(回溯算法-java)

在代码里,我们做出选择后,递归里 i + 1,我们去下一个位置去选择了,保证了,元素不重复,这个题目里,元素可以重复选择,因此,我们递归时,不传i + 1,传i 让他可以继续在这个位置上做出选择,这就解决了第一个问题,第二个问题,和为target,我们递归时带上这个target,每次选择一个数时,target 减去这个数,那么target == 0 时,代表目标和满足要求,停止选择就行了。注意 2 可以使用多次。输出: [[2,2,2,2],[2,3,3],[3,5]]输出:[[2,2,3],[7]]

SP_1024的博客 816

LeetCode 39:组合总和——Java DFS 回溯与剪枝详解

本文详细讲解了如何解决组合总和问题,即在给定无重复元素的正整数数组和目标值的情况下,找出所有数字之和等于目标的组合。文章通过决策树模型分析问题,强调使用DFS回溯算法和start参数来避免重复组合。核心思路是每层递归从指定位置开始选择数字,允许重复使用当前数字,并通过剪枝优化效率。文中提供了完整的Java代码实现,并通过示例演示执行过程,最后总结了常见错误和解题要点。该算法的时间复杂度与目标值相关,空间复杂度由递归深度决定。

weixin_51228134的博客 372

【回溯&剪枝】力扣Hot100:39. 组合总和题目解析(Java详解)

回溯法是解决组合类、排列类问题的常用技巧,理解递归和剪枝思想可以帮助你高效解决类似问题。文章标签:力扣,算法,Java,回溯,剪枝,面试,数组,递归。

weixin_46532327的博客 350

Java版LeetCode热题100之组合总和:回溯算法与剪枝优化的深度解析

组合总和是完全背包问题的回溯解法start参数是避免重复组合的关键排序 + 剪枝能大幅提升性能时间复杂度由输出规模决定,无法优化渐进复杂度。

吾为热爱计科,致力于知识分享的践行者,此博客是我在这条道路上留下的足迹。 1066

[Leetcode][第39题][JAVA][组合总和][回溯][dfs][剪枝]

【问题描述】[中等] 【解答思路】 1. 回溯 import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; public class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) {

dadongwudi的博客 343

Leetcode刷题java之39. 组合总和(回溯法以及回溯法框架)

执行结果: 通过 显示详情 执行用时 :3 ms, 在所有 Java 提交中击败了98.06% 的用户 内存消耗 :36.9 MB, 在所有 Java 提交中击败了91.67%的用户 回溯法框架:(这个框架是labuladong写的 回溯框架!!!) 1、路径:也就是已经做出的选择。 2、选择列表:也就是你当前可以做的选择。 3、结束条件:也就是到达决策树底层,无法再做选择的条件。 代...

逆水行舟,不进则退 926

leetcode216. 组合总和 III(回溯算法-java)

我们要的就是s_2 中的 [1,2] 这个结果,因此这个问题也和子集一样,同样可以用回溯算法的框架去解决。只是我们加上条件,筛选出s_2中的[1,2]在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。在回溯算法里,组合也是子集问题的拓展,是子集的一部分,子集问题可以查看。输出: [[1,2,6], [1,3,5], [2,3,4]]比如【1,2,3】 n = 3,k = 2。输入: k = 4, n = 1。输出: [[1,2,4]]

SP_1024的博客 1528

力扣第39题:组合总和(java回溯)

一、题目内容 二、题目分析 这道题目的示例[2,3,6,7],可以用下图方式遍历的理解。 如图,首先有四种选择方法,可以在2,3,6,7中任选一个,然后将它加到临时列表中去,之后每层都有四种选择方法(因为可重复选择),每次选择后我们用sum+=选择的值,当我们一直选择到sum等于target的时候,说明我们找到了一种情况满足条件,那我们就将这一临时列表加到结果列表里去,如果sum>target,则说明当前的值不应该选择,直接return即可。只有当sum...

少渊的博客 340

力扣39题:组合总和的 Java 实现

通过本文的介绍,你应该已经了解了如何使用 Java 解决力扣第39题“组合总和”。这个问题是一个很好的练习回溯算法的机会。希望本文能够帮助你更好地理解和掌握回溯算法。如果你有任何问题或需要进一步的帮助,请随时在评论区提问。

2301_77695569的博客 1052

leetcode:组合总和II(回溯java)

package LeetCode; import java.util.*; /* 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的每个数字在每个组合中只能使用一次。 说明: 所有数字(包括目标数)都是正整数。 解集不能包含重复的组合。 示例 1: 输入: candidates...

pioneer的博客 395
上一篇: leetcode:报数
下一篇: leetcode:组合总和II(回溯java)
ArchitectDream
博客等级 码龄9年 48粉丝 288原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值