首页 > 其他分享 >【刷题笔记】39. Combination Sum

【刷题笔记】39. Combination Sum

时间:2023-09-06 13:01:37浏览次数:31  
标签:39 set target Combination nums int res Sum candidates

题目

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

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

Note:

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

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

题目大意

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

解题思路

  • 题目要求出总和为 sum 的所有组合,组合需要去重。
  • 这一题和第 47 题类似,只不过元素可以反复使用。

参考代码

package leetcode

import "sort"

func combinationSum(candidates []int, target int) [][]int {
	if len(candidates) == 0 {
		return [][]int{}
	}
	c, res := []int{}, [][]int{}
	sort.Ints(candidates)
	findcombinationSum(candidates, target, 0, c, &res)
	return res
}

func findcombinationSum(nums []int, target, index int, c []int, res *[][]int) {
	if target <= 0 {
		if target == 0 {
			b := make([]int, len(c))
			copy(b, c)
			*res = append(*res, b)
		}
		return
	}
	for i := index; i < len(nums); i++ {
		if nums[i] > target { // 这里可以剪枝优化
			break
		}
		c = append(c, nums[i])
		findcombinationSum(nums, target-nums[i], i, c, res) // 注意这里迭代的时候 index 依旧不变,因为一个元素可以取多次
		c = c[:len(c)-1]
	}
}

标签:39,set,target,Combination,nums,int,res,Sum,candidates
From: https://blog.51cto.com/u_16110811/7385529

相关文章

  • No module named 'sklearn'解决方案
    sklearn深度学习库官方网站,打开之后按需复制命令进行安装,此处只列出两个最常用的:windows下pip安装:pipinstall-Uscikit-learnLinux下pip安装:pip3install-Uscikit-learnwindows/linux下conda安装:condainstall-cconda-forgescikit-learn ......
  • weblogic-10.3.6-'wls-wsat'-XMLDecoder反序列化漏洞-(CVE-2017-10271)
    目录1.1、漏洞描述1.2、漏洞等级1.3、影响版本1.4、漏洞复现1、基础环境2、漏洞扫描nacsweblogicScanner3、漏洞验证说明内容漏洞编号CVE-2017-10271漏洞名称Weblogic<10.3.6'wls-wsat'XMLDecoder反序列化漏洞(CVE-2017-10271)漏洞评级高危影响范围10.3......
  • ES中reverse_nested+sum+bucket_sort
    记一次嵌套sum聚合的排序DSL场景:根据nested_gs2Entity.kw_entity聚合,filter对聚合结果过滤类型是产品,实体是需要关心的产品列表,在结果中sum互动量long_interaction,和花费long_paidPrice然后在结果中根据sum的结果排序{"aggregations":{"agg_entity_a":{"aggre......
  • $('.panel-collapse').on('show.bs.collapse', function () {})详解
    $('.panel-collapse').on('show.bs.collapse',function(){});这段代码是在使用jQuery来绑定事件。$('.panel-collapse')部分是一个选择器,它选择了当前页面上所有有panel-collapse这个类的元素。如果你在HTML中有这样的元素:<divclass="panel-collapse"></div>,那么这......
  • LeetCode -- 394. 字符串解码(栈处理字符串问题)
     我们用栈同时维护当前字符串和倍数以及要加倍的字符串当遇到"["时,我们保存当前字符串,即将当前字符cres串入栈;当遇到"]"时,res=cres+倍数*应加倍的字符串classSolution:defdecodeString(self,s:str)->str:stack,res,multi=[],"",0......
  • 安装weditor时提示“ UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in po
    问题:安装weditor时提示“UnicodeDecodeError:'gbk'codeccan'tdecodebyte0xadinposition645:illegalmultibytesequence” 解决:方法一:解决方法一设置用户或者系统变量: 方法二:设置临时变量后再pipinstallsetPYTHONUTF8=1pipinstallweditor 原......
  • 删除文件报错rm: cannot remove `auditcommand.log': Operation not permitted
    删除文件报错[root@db1log]#rm-rfauditcommand.logrm:cannotremove`auditcommand.log':Operationnotpermittedlsattr查看属性[root@db1log]#rm-rfauditcommand.logrm:cannotremove`auditcommand.log':Operationnotpermitted[root@db1log]#lsat......
  • 力扣——1 [两数之和](https://leetcode.cn/problems/two-sum/)
    给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那两个整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。示例1:输入:nums=[2,7,11,15],tar......
  • [AIGC] a brief summary for this week, replica and localGPT
    Inthisweek,Iexperiencedtwomainprojects,replicaandlocalGPT.replicademo:Replicaistryingtobuildamodelhub.Ihaven'tdiveinitsstructureyet,butIwilldomoreresearchbecauseIbeliveit'llbemorepopularandwidelyused......
  • Failed to start bean 'documentationPluginsBootstrapper'; nested exception is jav
    2023-09-0322:53:53.622WARN20788---[main]ConfigServletWebServerApplicationContext:Exceptionencounteredduringcontextinitialization-cancellingrefreshattempt:org.springframework.context.ApplicationContextException:Failedtostartbean......