40. Combination Sum II---找出和为target的子数组
来源:互联网 发布:崩坏3矩阵空间攻略 编辑:程序博客网 时间:2024/05/21 22:28
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]]
因为这道题需要去遍历所有的情况,这里选用了深度优先搜索,百度百科给出的深度优先搜索的基本思路如下:
深度优先遍历图的方法是,从图中某顶点v出发:
(1)访问顶点v;
(2)依次从v的未被访问的邻接点出发,对图进行深度优先遍历;直至图中和v有路径相通的顶点都被访问;
(3)若此时图中尚有顶点未被访问,则从一个未被访问的顶点出发,重新进行深度优先遍历,直到图中所有顶点均被访问过为止。 当然,当人们刚刚掌握深度优先搜索的时候常常用它来走迷宫.事实上我们还有别的方法,那就是广度优先搜索(BFS).
首先新建一个嵌套list,这是用于保存最后的结果,然后对cand数组进行排序,这样方便后面的遍历以及判断重复的值, 调用dfs函数即可得到结果;
dfs函数终结的条件是target为0或者target<0,用return;终结函数的递归调用并返回到上一级dfs函数,只有当target为0时才把list
添加到res中,当递归调用到dfs函数时,for循环的i起始值增加1,然后在cand数组中向后搜索,知道dfs调用终止,这时候说明找到了
我们需要的子数组或者target已经小于0,就执行remove语句,把不符合条件的数字删除,比如数组中添加的是[1,1,2]那么遇到5的时候
list变为[1,1,2,5]这时target<0,那么dfs终止,删除5,接着i+1于是把6添加到[1,1,2]中,变为[1,1,2,6],这样依然不满足,继续搜索即可
,代码如下:
public class CombinationSum2 {public static List<List<Integer>> combinationSum2(int[] cand, int target){List<List<Integer>> res = new ArrayList<List<Integer>>();List<Integer> list = new ArrayList<>();Arrays.sort(cand);dfs(cand,0,target,res,list);return res;}public static void dfs(int [] cand,int start,int target,List<List<Integer>> res,List<Integer> list){if(target==0){res.add(new ArrayList<Integer>(list));return;}if(target<0){return;}for(int i=start;i<cand.length;i++){if(i>start&&cand[i]==cand[i-1]) continue;list.add(list.size(),cand[i]);dfs(cand,i+1,target-cand[i],res,list);list.remove(list.size()-1);}}}
- 40. Combination Sum II---找出和为target的子数组
- [LeetCode]-Combination Sum I&II 求相加和为target的集合
- Combination Sum II 无序数组中找组合(每个元素只能用一次)使得和为target@LeetCode@LeetCode
- Combination Sum II:允许重复的数组中选取若干元素使和为某一给定值
- 【Leetcode】39. Combination Sum和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
- SearchView的使用说明
- Java设计模式之--适配器模式
- java基础(4)集合框架(一)
- SpringMVC与 Struts2
- c语言实现简单单链表
- 40. Combination Sum II---找出和为target的子数组
- Android如何减少apk大小
- Android 使用shape定义不同控件的的颜色、背景色、边框色
- opencv之轮廓的查找与绘制(二)
- MySQL备份方案-->(利用mysqldump以及binlog二进制日志)
- 阿里云上部署 WordPress 小结
- [leetcode]: 532. K-diff Pairs in an Array
- 专业实习01
- :last-child与:last-of-type你只是会用,有研究过区别吗?