Leetcode 39. Combination Sum (递归)

Leetcode 39. Combination Sum --数组元素组合,和为目标值,一个元素可用无数次,输出每种组合,每种组合唯一 Given asetof candidate numbers (candidates)(without duplicates)and a target number (target), find all unique combinations incandidateswhere the candidate numbers sums totarget. Thesamerepeat... 阅读详情

39. Combination Sum

 Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

题目链接:https://leetcode.com/problems/combination-sum/description/
题目大意:给定一个数组和一个目标数字。求数组中和为目标数字的所有数字组合,数字可以重复相加。
解题思路:dfs递归,到最底层若满足条件就把数字组合加入答案集合。
代码如下:
class Solution {
public:
    vector<vector<int> > ans;
    vector<int> ca;
    int n;
    void dfs(int st,vector<int> a,int cur,int target){  
        if(cur == target){
            ans.push_back(a);  //a是每个可能的答案,如果最终满足条件,即a中所有数字和为target,则把a加入答案数组
            return;
        }
        if(st >= n)
            return;
        for(int i = st;i < n;i++){
            if(cur + ca[i] <= target){
                int num = 1;
                vector <int> b = a;
                while(cur + ca[i] * num <= target){   //数字可以重复,多次加入同一个数字
                    b.push_back(ca[i]);
                    dfs(i + 1,b,cur + ca[i] * num,target);  //i是起始位置 
                    num ++;
                }
            }
        }
    }
    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
        n = candidates.size();
        ca = candidates;
        vector<int> a;
        sort(ca.begin(),ca.end());   //排序
        unique(ca.begin(), ca.end());   //去重
        dfs(0,a,0,target);  
        return ans;
    }
};



ZYNQ RFSoC 的DAC如何做到从 0到Fs频段 信号输出 之前一直没太了解 RFSoC 的DAC如何输出在 Fs/2 到 Fs 频率范围内的信号,例如 ZCU216中的 ZU49DR,其RF-DAC最大采样率是 9.85GSPS,如果想输出的信号中心频率在5.8G,它是如何有效输出在第二奈奎斯特区域范围的信号的。 阅读详情

相关推荐

STM32F103上跑mbedtls 2.24.0:手把手教你为MQTTS加密通信打好基础

本文详细介绍了如何在STM32F103上移植和裁剪mbedtls 2.24.0,为MQTTS加密通信打下坚实基础。通过版本选择、开发环境配置、深度裁剪策略和加密功能验证,帮助开发者在资源受限的MCU上实现安全通信。文章还提供了常见问题解决方案和性能优化技巧,助力物联网设备开发。

weixin_30321709的博客 474

leetCode 39.Combination Sum(组合总和) 解题思路和方法

Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from

Android进阶 5043

ARM Memory Compiler实战指南:从参数配置到GDSII生成的全流程解析

本文详细解析了ARM Memory Compiler在SRAM设计中的全流程应用,从基础参数配置到GDSII文件生成。涵盖SRAM类型选择、核心参数配置策略、高级优化技巧及TSMC 28nm工艺下的实战案例,帮助IC设计工程师高效实现存储器模块的优化设计。

game4的博客 440

leetcode 39. Combination Sum-回溯算法|递归|非递归

原题链接:39. Combination Sum 拓展博文:Combination Sum II | Java最短代码实现 【思路】 基本思路是先排好序,然后每次递归中把剩下的元素一一加到结果集合中,并且把目标减去加入的元素,然后把剩下元素(包括当前加入的元素)放到下一层递归中解决子问题。算法复杂度因为是NP问题,所以自然是指数量级的: public List> combina

hdtopku 4543

磁芯材质、形状、厂家汇总

速查磁芯形状和厂家

weixin_43143389的博客 392

Deep Reinforcement Learning - 1. DDPG原理和算法

Deep Reinforcement Learning - 1. DDPG原理和算法 背景描述 DDPG的定义和应用场景 DDPG算法相关基本概念定义 DDPG实现框架和算法 DDPG对于DPG的关键改进 下一篇 以下用RL作为Reinforcement Learning 的简称。背景描述概括来说,RL要解决的问

kenneth_yu的博客 14万+

LeetCode 39:组合(递归回溯)

LeetCode 39:组合 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不...

Sword1996的博客 293

YOLOv8改进策略【注意力机制篇】| CVPRW-2024 分层互补注意力混合层 H-RAMi 针对低质量图像的特征提取模块

许多证据表明层次化网络对图像恢复(IR)任务通常不太有效,因为IR的目标是逐个预测像素值(密集预测),而缩小特征图会丢失重要的像素级信息。然而,层次化结构有降低时间复杂度以及学习语义级和像素级特征表示的优点。为了弥补缺点并利用优点,设计了H - RAMi层。

Limiiiing的博客 384

Leetcode 39:组合总和(最详细的解法!!!)

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。 示例 1: 输入: candidates = [2,3,6,7], target = 7, 所求...

coordinate的博客 1万+

YOLOv11涨点改进| CVPR 2026 | 全网独家首发、特征融合改进篇| 引入SRFusion 空间细化多级融合,含多种创新融合改进,涨点可直接发论文,适合裂缝图像检测,小目标检测任务高效涨点

🔥本文提出SRFusion空间细化多级融合模块,用于改进YOLOv11网络模型。该模块通过高分辨率特征引导低分辨率语义特征的融合,利用空间注意力机制对上采样后的特征进行加权细化,增强多尺度特征间的空间细节交互。SRFusion模块能够提升模型对目标区域的表达能力,有效改善小目标、密集目标及复杂背景场景下的检测效果,同时保持YOLOv11的高效性与实时检测性能。文章详细介绍了模块结构、实现原理、核心代码及在YOLOv11中的三种配置方法,为模型优化提供了创新解决方案。

Ai缝合怪、助力小伙伴高效发论文 155

Python和Spyder:一个完美的编程组合

而Spyder作为一个专门为科学计算和数据分析而设计的IDE,提供了高效的开发环境和丰富的工具。无论是初学者还是专业开发者,Python和Spyder都能满足他们的需求,并为他们的工作带来便利和效率。本文将探讨Python和Spyder之间的关系,以及它们如何相互配合,提供一流的编程体验。每个工具都有其特定的优势和适用场景,开发者可以根据自己的需求选择合适的工具。而Spyder作为一个专门为科学计算而设计的IDE,提供了编写、调试和执行Python代码的环境。

CodeHeroicX的博客 1131

leetcode39. 组合总和

题目: 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 思路: 回溯+递归; 为了提高效率,可以先对数组排序,然后当遇到sum>target时就直接跳出循环,因为后面的肯定都不可以了; 代码中sum和candidates[i]不能提前相...

一个小白的日常 1105

(三十九)Flask 多应用架构(Multiple Apps)与 DispatcherMiddleware 实战解析

(三十九)Flask 多应用架构(Multiple Apps)与 DispatcherMiddleware 实战解析

孤寒者的博客 1万+

LeetCode 39. Combination Sum 题解

本题是回溯算法的经典问题,主要考察对回溯思想的理解和应用。通过维护一个路径数组和起始索引,我们可以生成所有可能的组合,并确保不重复。回溯算法的核心思想是:通过选择、递归、回溯的过程,遍历所有可能的解空间,找到符合条件的解。可以重复选择同一元素,因此递归调用时起始索引仍为当前索引。为了避免重复组合,我们从起始索引开始遍历,而不是从数组的开头。当当前和大于目标值时,停止继续选择,进行剪枝,提高效率。这种方法不仅适用于组合总和问题,还可以应用于许多其他组合问题,例如子集问题、排列问题等。

cannonjinx的博客 4396

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

39.leetcode Combination Sum(medium)[递归回溯]

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited numb

qz530308783的专栏 243

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

【小白爬Leetcode39】数组总和 Combination Sum

【小白爬Leetcode39】数组总和 Combination Sum题目方法一 暴力搜索(反例,不完全递归)方法二 回溯方法三 剪枝 题目 Leetcode39 medium\color{#ffaa00}{medium}medium 点击进入原题链接:数组总和 Combination Sum Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find al

weixin_41604040的博客 221

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

LeetCode 39. Combination Sum and LeetCode 40. Combination Sum II

LeetCode 39. Combination Sum Description: Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums t...

My Blog 235

[leetcode javascript解题]Combination Sum

leetcode第39题Combination Sum描述如下: Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The sam

zzxboy1的博客 784

40. Combination Sum II

题目 Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. Each number in candidates m...

努力学习的姜饼 110

LeetCode 39.数组总和 Combination Sum

题目链接 中文 https://leetcode-cn.com/problems/combination-sum/description/ 英文 https://leetcode.com/problems/combination-sum/description/ 解题思路 1.首先对candidates进行排序,这样可以在循环遍历时先取到小的加数,保证加数有效性,并且可以在加数较大时直接退出循环,...

qq_32147775的博客 368

leetcode 39. Combination Sum DFS深度优先搜索 + 按照index做递归

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from...

JackZhangNJU的专栏 704

LeetCode 39. Combination Sum 题解(回溯 / DFS)

给定一个由互不相同的正整数构成的数组 candidates,以及一个目标值 target,找出所有可以使数字和为 target 的组合。数组中的数字可以被重复选择任意次,但组合之间不能重复,返回结果的顺序可以任意。

六六哥的博客 372

LeetCode刷题:39. Combination Sum

LeetCode刷题:39. Combination Sum 原题链接:https://leetcode.com/problems/combination-sum/description/ Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique comb...

梅森上校的博客 业精于勤荒于嬉,形成于思毁于随。 286

Leetcode 39 Combination Sum

Leetcode 39 Combination Sumclass Solution { public: vector<vector<int>> sum; vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<int> result; sort(can

自己的学习笔记 210

LeetCode(40) Combination Sum II

在LeetCode(39) Combination Sum代码基础上增加了一些代码。具体分析参见LeetCode(39) Combination Sumclass Solution { public: void dfsSearch(vector<int> &candidates, int serialNumber, vector<int> &combinationIndex, int dept

一只不断成长的藏獒 318

39. Combination Sum

/* * 39. Combination Sum * 2016-5-3 by Mingyang * The same repeated number may be chosen from C unlimited number of times. * 注意在实现中for循环中第一步有一个判断,那个是为了去除重复元...

weixin_30401605的博客 87
上一篇: Leetcode 15. 3Sum
下一篇: Leetcode 46. Permutations (全排列)
雨狮子
博客等级 码龄12年 24粉丝 185原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址