问题原始链接 https://leetcode.com/problems/combination-sum
给定一个整数集合C和一个目标数T,找到C中所有和等于T的数的组合。C中的每个数可以取任意多次。
注意:
所有数字都是正整数。
结果中不能包含重复的组合。
例如,给定集合 [2,3,6,7] 和目标值7。
结果是:
[
[7]
[2,2,3]
]
public class Solution {
public static List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (candidates == null || candidates.length == 0) {
return result;
}
Arrays.sort(candidates);
List<Integer> temp = new ArrayList<Integer>();
combinationSum(candidates, target, candidates.length - 1, temp, result);
return result;
}
private static void combinationSum(int[] candidates, int target, int i,
List<Integer> temp, List<List<Integer>> result) {
for (int j = target / candidates[i]; j >= 0; j--) {
if (i == 0) {
if (target == candidates[i] * j) {
List<Integer> r = new ArrayList<Integer>(temp);
for (int k = 0; k < j; k++) {
r.add(candidates[i]);
}
result.add(r);
}
} else {
List<Integer> t = new ArrayList<Integer>(temp);
for (int k = 0; k < j; k++) {
t.add(candidates[i]);
}
if (target == j * candidates[i]) {
result.add(t);
} else {
int k = i - 1;
while (k >= 0 && candidates[k] == candidates[i]) {
k--;
}
if (k >= 0) {
combinationSum(candidates, target - j * candidates[i], k, t, result);
}
}
}
}
}
}