Combination Sum:非重复数组中选取若干元素求和等于给定值
来源:互联网 发布:豫章学院 知乎 编辑:程序博客网 时间:2024/06/05 14:36
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 { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> list = new ArrayList<>(); Arrays.sort(candidates); dfs(candidates,0,0,target,list); return list; } static int[] index = new int[10000]; public static void dfs(int[] candidates,int sum,int i,int target,List list){ if(sum>target) return; if(sum==target){ ArrayList<Integer> l = new ArrayList(); for(int j=0;j<candidates.length;j++){ if(index[j]!=0){ for(int c = index[j];c>0;c--){ l.add(candidates[j]); } } } list.add(l); return; }else{ for(int j = i ;j<candidates.length;j++){ index[j]++; dfs(candidates,sum+candidates[j],j,target,list); index[j]--; } } } }
阅读全文
0 0
- Combination Sum:非重复数组中选取若干元素求和等于给定值
- Combination Sum II:允许重复的数组中选取若干元素使和为某一给定值
- Combination Sum III:从0-9中选取K个数求和等于n
- 求数组中若干个元素之和等于给定值
- 4Sum:带重复数组取值求和
- 3Sum:带重复数组中取三个元素求和为零
- 取若干个数求和等于k
- Combination Sum求和为给定值的所有序列的解题思路
- Combination Sum求和为给定值的所有序列的解题思路(续)
- 递归列举从数组b()中选出某些元素(允许重复)使其和等于num的所有组合
- 返回两个求和等于给定值的数组下标--算法练习
- 从给定的N个正数中选取若干个数之和最接近M
- 给定的N个正数中选取若干个数之和最接近M
- 面试题:从给定的N个正数中选取若干个数之和最接近M
- 从给定的N个正数中选取若干个数之和最接近M
- 从给定的N个正数中选取若干个数之和为M
- 面试题:从给定的N个正数中选取若干个数之和最接近M
- Combination Sum II 全排列求和无重复
- <序列DP>O(nlogn)的最长上升子序列
- 整体二分小结
- bfs学习之寻找二叉树每层最大值
- detect获取到手机型号
- CopyOnWriteArrayList----ReadWriteLock---ConcurrentHashMap
- Combination Sum:非重复数组中选取若干元素求和等于给定值
- Jmeter之处理session、cookie以及如何做关联
- postMessage方法使app内嵌页面跳转原生页面
- MNIST和softmax回归模型
- Increasing Triplet Subsequence
- rollbackFailedOptional: verb npm-session 问题
- 清北学堂-D6-T1-divisors
- 【yum命令】软件包管理器
- 关于visual studio code在win10系统上安装后会报扩展宿主意外终止的解决方法