40. Combination Sum II---找出和为target的子数组

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);
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值