39. Combination Sum (Java)
2024-09-03 13:59:54
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]
]
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> ans = new ArrayList<Integer>();
Arrays.sort(candidates);
backTrack(candidates, target, 0, ans, 0);
return result;
} public void backTrack(int[] candidates, int target, int start, List<Integer> ans, int sum){
if(start >= candidates.length || sum + candidates[start] > target)
return; //not found
else if(sum + candidates[start] == target ){ //found an answer
List<Integer> new_ans = new ArrayList<Integer>(ans); //不能用List<Integer> new_ans = ans;这个只是创建了原List的一个引用
new_ans.add(candidates[start]);
result.add(new_ans);
}
else{
// not choose current candidate
backTrack(candidates,target,start+1,ans,sum); //choose current candidate
ans.add(candidates[start]);
backTrack(candidates,target,start,ans,sum+candidates[start]);
ans.remove(ans.size()-1); //List是按引用传递,为了不影响递归,需要复原
}
} private List<List<Integer>> result = new ArrayList<List<Integer>>();
}
注意List按引用(地址)传递,需要新new一个,或是复原,以不影响其他部分
最新文章
- GetViewUrl
- Sql Server系列:数据库对象
- Linux下压缩音频文件
- sql2008“备份集中的数据库备份与现有的xxx数据库不同”解决方法
- 64. ZigZag Conversion
- IE下angularJS页面跳转的bug
- 网页撤销后ubuntu本地撤销
- 20145236 《Java程序设计》实验一实验报告
- 关于iOS自定义UITabBar的几种方法
- 简单对比Spark和Storm
- 解决Boost.Regex对中文支持不好的问题
- U盘装centos7系统过程
- Spring 控制反转
- IOS学习2——Xcode快捷键大全
- How 5 Natural Language Processing APIs Stack Up
- Django中怎么做图片上传--图片展示
- 线性代数导论 | Linear Algebra 课程
- ranch 源码分析(完)
- pymysql 读取数据库没有字段
- 用H5上传文件
热门文章
- 通过jedis连接redis单机成功,使用redis客户端可以连接集群,但使用JedisCluster连接redis集群一直报Could not get a resource from the pool
- vscode-php代码提升及函数跳转
- legend3---阿里云如何多个域名指向同一个网站
- udp组播的实现
- 九、SpringBoot集成Thymeleaf模板引擎
- 2 日志系统:一条sql更新语句是如何执行的?
- 【Linux 应用编程】文件IO操作 - 常用函数
- 20191127 Spring Boot官方文档学习(4.14-4.17)
- 【css】子元素浮动到了父元素外,父元素没有随子元素自适应高度,如何解决?
- 更新代码 出现 You need to upgrade the working copy first 错误