组合总和
问题:
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] ]
解决:
① 结果要求返回所有符合要求解的题十有八九都是要利用到递归,而且解题的思路都大同小异,需要另写一个递归函数。注意是可以连续选择同一个数加入组合的。与方法②一样
class Solution { //17 ms
public static List<List<Integer>> combinationSum(int[] candidates, int target){
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
dfs(candidates,0,target,cur,res);
return res;
}
private static void dfs(int[] candidates, int i, int target, List<Integer> cur, List<List<Integer>> res) {//i表示当前遍历到的下标。
if(target < 0) return;
if(target == 0){
res.add(new ArrayList<>(cur));
return;
}
for(int j = i; j < candidates.length && target >= candidates[j]; j ++){
cur.add(candidates[j]);
dfs(candidates,j,target - candidates[j],cur,res);//递归向后查找
cur.remove(cur.size() - 1);//还原链表
}
}
}
② 简化
class Solution { //19ms
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<Integer> cur = new ArrayList<>();
dfs(candidates, 0, target, cur);
return res;
}
private void dfs(int[] nums, int i,int target, List<Integer> cur) {//i表示当前遍历到的位置
if (target == 0) {
res.add(new ArrayList<>(cur));
// return;
}
for (int j = i; j < nums.length; j ++) {
if (nums[j] <= target) {
cur.add(nums[j]);
dfs(nums, j, target - nums[j], cur);
cur.remove(cur.size() - 1);
}
}
}
}
推荐阅读
-
今日纳米:沈阳药科大学孙进/孙秉军团队继续探索三硫化-键桥原药纳米组合体
-
Mobile Telecom 推出另一系列高性能卫星、5G、GNSS 和三合一组合天线
-
新手组合 - StreamPark + Paimon 的最佳实践 - Paimon 的核心功能
-
基于 H.264 的 RTP 分组和数据包捕获分析中的组合数据包和分割数据包结构介绍
-
PHP 数组合并时,如何分割合并后的数组?
-
如何处理 PHP 数组合并后的空数组?
-
字节跳跃组合:左手 C 端,右手 B 端
-
任选 1-10 中的 4 个数字,用加减乘除计算可能的 24 种结果组合(java 版),很多人小时候都玩过!
-
Python3 分析多股票投资组合
-
中科院背景的团队,恩谷如何打好 "科技+服务 "的养老组合拳?