Combination Sum II:允许重复的数组中选取若干元素使和为某一给定值
来源:互联网 发布:da8da六爻排盘软件 编辑:程序博客网 时间:2024/06/16 23:42
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6]]
例如1,1,1,1 target为2,输出[1,1]
思路:按照dfs遍历。麻烦的是元素中可能存在重复的元素,但结果里去不能有重复的结果。所以两种办法:第一种是穷举所有结果,再去重;第二种是便利时就不考虑重复结果。第二种更方便一些。
下图是一个例子,圆圈与方框是表示当前已保存的元素,三角是正在遍历的元素,圆圈与方框中元素相同即被看成是同一种情况。
class Solution { public List<List<Integer>> combinationSum2(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){ l.add(candidates[j]); } } list.add(l); return; }else{ for(int j = i ;j<candidates.length;j++){ if(j>i&&candidates[j]==candidates[j-1]) continue; index[j]++; dfs(candidates,sum+candidates[j],j+1,target,list); index[j]--; } } }}
阅读全文
0 0
- Combination Sum II:允许重复的数组中选取若干元素使和为某一给定值
- Combination Sum:非重复数组中选取若干元素求和等于给定值
- 递归列举从数组b()中选出某些元素(允许重复)使其和等于num的所有组合
- 从给定的N个正数中选取若干个数之和为M
- 167. Two Sum II - Input array is sorted (在有序数组中确定和为给定值的两个元素的下标)
- 深度优化搜索 ---判断是否可以从给定整数中选出若干数,使它们的和恰好为k
- Combination Sum II 无序数组中找组合(每个元素只能用一次)使得和为target@LeetCode@LeetCode
- 40. Combination Sum II---找出和为target的子数组
- LeetCode | Combination Sum II(元素的和---2)
- 1. Two Sum 给定一个数组和一个数,输出两个和为给定数的数组元素的下标
- 在给定的数组中找出两个元素和为给定值的所有元素对
- 在给定的数组中找出两个元素和为给定值的所有元素对
- Combination Sum II 组合数之和(包含有重复的元素)
- 167 Two Sum II (给定数组求相加为定值的两个数)
- 在给定数组中查找两个数的和为给定值sum
- 从给定的N个正数中选取若干个数之和最接近M
- 给定的N个正数中选取若干个数之和最接近M
- 面试题:从给定的N个正数中选取若干个数之和最接近M
- 7.oracle函数
- 16通道24位分辨率x8 PCIE 3U PXIE采集卡
- Codeforces 270E Flawed Flow【思维+类拓扑排序】
- 【第二周周练 H 】
- 【NOIP2013初赛】整除
- Combination Sum II:允许重复的数组中选取若干元素使和为某一给定值
- 初识GP
- 树莓派键盘布局设置入坑与出坑
- 【python】二进制转换
- CodeForces
- 顺序表ADT实现(带注释)
- 一小时学会搭建网站
- 8.oracle 复杂表查询
- jQuery设计思想