40. Combination Sum II
来源:互联网 发布:电视猫yunos优化版 编辑:程序博客网 时间:2024/05/16 14:48
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]]
思路:
既然数组中存在重复的值,就要注意可能会将重复的情况加入结果数组。例如,如果数组为[2,2,2,6],目标值为8,可能会在结果数组中出现多次[2,6]。
同样的,在进行递归的子遍历的时候也要注意,可能会出现重复值,例如数组为[2,2,2,6],目标值为10,则结果集[2,2,6]也可能出现多次,所以在子遍历中也要记得去除重复情况。
class Solution { List<List<Integer>> result = new ArrayList<List<Integer>>(); public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); int length = candidates.length; for(int i = 0 ; i < length ; i++){ //去除外围重复情况 if(i > 0 && candidates[i] == candidates[i-1]){continue;} if(candidates[i] == target){ result.add(Arrays.asList(candidates[i])); }else{ List<Integer> temp = new ArrayList<Integer>(); temp.add(candidates[i]); combinationSum2(candidates, target-candidates[i], i + 1, temp); } } return result; } public void combinationSum2(int[] candidates, int target, int startAt, List<Integer> currentList){ for(int i = startAt ; i<candidates.length ; i++){ if(candidates[i] == target){ currentList.add(candidates[i]); result.add(currentList); return; } if(candidates[i] > target){ return; } if(candidates[i] < target){ List<Integer> temp = new ArrayList<Integer>(currentList); temp.add(candidates[i]); combinationSum2(candidates, target-candidates[i], i + 1, temp); } //去除自遍历中的重复情况 while(i < candidates.length - 1 && candidates[i] == candidates[i + 1]){i++;} } }}
阅读全文
0 0
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- 40. Combination Sum II
- stm8 stvd生成.o文件和lef文件
- OSGI框架常用控制台命令
- 单词拆分 I
- dubbo服务管理中间件底层原理
- 2017年浙江工业大学大学生程序设计迎新赛决赛—网络同步赛 J 栗酱和火柴【water】
- 40. Combination Sum II
- 雇员管理系统-SSH版(七)
- 微信小程序留言功能实现
- CheckBox 简单使用
- 10.8、spring boot的web应用——servlet、listener、filter的应用
- 2017年浙江工业大学大学生程序设计迎新赛决赛—网络同步赛 K qwb的骚扰【分类讨论】
- bzoj3879 SvT(后缀数组+单调栈)
- python向mysql数据库插入汉字出现乱码问题
- 2017年浙江工业大学大学生程序设计迎新赛决赛—网络同步赛 L qwb与电阻【dfs】