题目原型:
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:
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
原文:http://blog.csdn.net/cow__sky/article/details/22187123