题意:给定一个集合C,与一个数值target,找出所有满足和为target的集合。(且每次求和时,C中的元素不能够重复使用)
注意:1.集合中的所有元素都是正的
2.得出的集合不能够重复
例如: C = {10,1,2,7,6,1,5} target = 8
结果:
[
[1,7]
[2,6]
[1,2,5]
[1,1,6]
]
具体实现代码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HelloWorld {
//用于测试的主方法
public static void main(String[] args) {
int[] arrays = {10,1,2,7,6,1,5};
int target = 8;
getCombinationSum1(arrays, target);
System.out.println(combinationSum1.toString());
}
public static List<List<Integer>> combinationSum1 = new ArrayList<>();
public static void getCombinationSum1(int[] arrays, int target) {
//步骤一 将数据排序
Arrays.sort(arrays);
//递归求和
combinationSum(arrays, 0, 0, new ArrayList<Integer>(),target);
}
/**
* 求和,使得和为target(arrays中元素可以重复使用)
*
* @param arrays 总的元素
* @param start 开始计算的位置
* @param sum 当前已有元素的和
* @param currentAdderForSum 当前和为sum是的元素元素组成
* @param target 目标的值
*/
private static void combinationSum(int[] arrays, int start, int sum, ArrayList<Integer> currentAdderForSum, int target) {
if (sum == target) { //当前的集合已经满足和为target的要求,则将数据存储一下
combinationSum1.add(new ArrayList<>(currentAdderForSum)); //注意这里一定要重新New集合
return;
}
for (int i = start; i < arrays.length; i++) {
//如果集合中有重复元素则为了避免重复,跳过本次循环
if (i > start && arrays[i] == arrays[i - 1]) {
continue;
}
if ((sum + arrays[i]) > target) {
//因为这是一个经过排序之后的升序数组,再接下来遍历循环没有意义,因此退出循环
break;
}
currentAdderForSum.add(arrays[i]);
//与《leecode刷题 之 39 Combination Sum》中不同,因为本题中 集合中元素不可以无限使用
combinationSum(arrays, i + 1, sum + arrays[i], currentAdderForSum, target);
currentAdderForSum.remove(currentAdderForSum.size() - 1);
}
}
}
运行结果如下:
与leecode刷题 之 39 Combination Sum相对,本题不允许元素无限使用。所以
//在进行递归调用的使用,传入i+1,leecode 39中传入的是i
combinationSum(arrays, i + 1, sum + arrays[i], currentAdderForSum, target);