Combination Sum II
2015-05-31 09:54
579 查看
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.
Elements in a combination (a1, a2,
… , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
… ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
A solution set is:
思路:与Combination Sum的区别是要考虑到去重,因为数字可能会重复,那么选出的两个子集合也可能会重复。考虑去重的话,就是在当前元素被删除的时候,也就是当前元素没有被选中,如果下一个数字与当前数字是相同的,那选择下一个数字也是没有意义的,直接跳过下一个数字,从下下个数字开始选择。
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.
Elements in a combination (a1, a2,
… , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤
… ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set
10,1,2,7,6,1,5and target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
思路:与Combination Sum的区别是要考虑到去重,因为数字可能会重复,那么选出的两个子集合也可能会重复。考虑去重的话,就是在当前元素被删除的时候,也就是当前元素没有被选中,如果下一个数字与当前数字是相同的,那选择下一个数字也是没有意义的,直接跳过下一个数字,从下下个数字开始选择。
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> res =new ArrayList<List<Integer>>(); select_sum(candidates,0,target,new ArrayList<Integer>(),res); return res; } //从candidates中选出数字使得所选出数字的和为target,temp作为所选出数字的临时栈,idx代表candidates的下标 public void select_sum(int[] candidates, int idx, int target,List<Integer> temp, List<List<Integer>> res) { if (target<0) return; //如果target,说明所选出数字的和为target,就将temp添加到res中 if (target==0) { List<Integer> temp_new = new ArrayList<Integer>(temp); if(temp_new.size()==0) return; res.add(temp_new); return; } if (idx >= candidates.length) return; //如果当前数字被选中,下标应该从idx+1开始,选出的剩下的数字的和为target-candidates[idx] temp.add(candidates[idx]); select_sum(candidates, idx+1, target-candidates[idx], temp, res); //如果当前数字没有被选中,删除已经添加进去的数字,那就从下一个数字开始选择 temp.remove(temp.size() - 1); //但是如果下一个数字和当前没有被选中的数字相等的话,那就直接跳过下一个数字,也就是去重 while(idx<candidates.length-1&&candidates[idx+1]==candidates[idx]) idx++; select_sum(candidates, idx+1, target, temp, res); } }
相关文章推荐
- Fedora10 配置使用root用户登录
- mybatis连接mysql数据库实现的jdbc功能
- Floyd算法,求图中两个点之间的最短距离
- 利用ListView实现新闻客户端的新闻内容图文混排
- TL 栈,队列,优先队列用法
- KBMMW 4.82.00 发布
- java个人学习笔记:位运算符
- 最小顶点数就能覆盖所有边==二分图的最大匹配
- 给老师的建议?????
- NOI2005 维修数列(综合包括求区间的最大值)---Splay
- PostgreSQL function里面调用function
- hdu3487 (splay伸展树 区间翻转,切割,插入)
- Combination Sum
- Android TextView里直接显示图片的三种方法
- HTML 表单(form) 使用详解
- Redhat6.2升级为Redhat6.3 (linux内核升级)
- 回调函数理解-以Fragment为例
- Android UI开发: 横向ListView(HorizontalListView)及一个简单相册的完整实现 (附源码下载)
- NOI2004 郁闷的出纳员
- Java web基础总结十之—— jsp EL表达式