首页 > 其他 > 详细

Combination Sum

时间:2014-03-26 18:07:02      阅读:503      评论:0      收藏:0      [点我收藏+]

题目原型:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

基本思路:

这题比较简单,明显的递归回溯,只要保证下一层的开始元素是这一层的结束元素即可。

	ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();

	public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates,
			int target)
	{
		if (candidates == null || candidates.length == 0)
			return list;
		if (target < 0)
			return list;
		//排序数组
		Arrays.sort(candidates);
		combinationSum(candidates, target, new ArrayList<Integer>(), 0);
		return list;
	}

	public void combinationSum(int[] candidates, int target,
			ArrayList<Integer> num, int startIndex)
	{
		if (target < 0)
			return;
		if (target == 0)
		{
			list.add(new ArrayList<Integer>(num));
			return;
		}
		for (int i = startIndex; i < candidates.length; i++)
		{
			num.add(candidates[i]);
			combinationSum(candidates, target - candidates[i], num, i);
			num.remove(num.size() - 1);//必须移除,否则影响下一步
		}
	}



Combination Sum,布布扣,bubuko.com

Combination Sum

原文:http://blog.csdn.net/cow__sky/article/details/22187123

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!