题目:
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 (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 2,3,6,7
and target 7
,
A solution set is:
[7]
[2, 2, 3]
这道题与之前的2Sum,3Sum,4Sum很相似,但这里加数的个数并没有给定,而且C中元素还可以不限次数的使用,在这么庞大的解空间里寻找所有答案,考虑使用分治算法。
首先对C进行排序,这样可以使得待会回溯时,较小的元素始终在前面。
接下来的问题问题可以分为两个子问题,以{2,3,6,7},7为例:包含第一个元素的所有解{2,3,6,7},5,和不包含第一个元素的所有解{3,6,7},7,开始递归,递归结束的条件是:
1、若target=0,则问题找到一组解,把当前的路径保存加入list集合中;
2、若target<0,则问题求解失败,回溯到上一状态,尝试下一种可能;
3、若集合C中已经没有第一个元素,则回溯到上一状态,尝试下一种可能。
注意这里没有用ArraList保存路径是因为在求解过程中要不停的更改ArrayList的值,这样会难以控制,所以偷懒用String来保存路径了- -!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class No38_CombinationSum {
public static void main(String[] args){
System.out.println(combinationSum(new int[]{1}, 1));
}
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> list = new ArrayList<List<Integer>>();
String s = "";
fun(candidates, target, 0, list, s);
return list;
}
public static void fun(int[] candidates, int target, int i, List<List<Integer>> list, String s){
if(target<0){
return;
}
if(target == 0){
List<Integer> element = new ArrayList<Integer>();
String[] sa = s.split(",");
for(int k=1;k<sa.length;k++){
element.add(Integer.valueOf(sa[k]));
}
list.add(element);
return;
}
if(i >= candidates.length)
return;
fun(candidates, target, i+1, list, s);
fun(candidates, target-candidates[i], i, list, s+","+candidates[i]);
}
}