卡在组合问题 [英] Stuck with Combination Problem
问题描述
我的程序有问题.我已经提取了一组数据,我想测试一下特定数字是否存在组合.例如,我有一个int数组,即1 2 3 4 5,我想知道是否存在7的组合,它必须回答是3 + 4.
I'm having a problem w/ my program. I have extracted a set of data and I would like to test if there is a combination for a particular number. For example, I have an array of int, 1 2 3 4 5, I would like to know if there is a combination for 7 maybe, and it must answer yes there is 3 + 4.
我发现我需要使用组合公式.因此,我认为外循环可能类似于5C1..5C2..5C3..etc,开始先取1"然后取2",以找出所有可能的组合.问题是我被困在如何在实际代码中实现这一点.
I figured out that I need to use the combination formula. So I thought that the outer loop may go like 5C1..5C2..5C3..etc, starting to "take 1" then "take 2" at a time to find out all the possible combinations. The problem is I'm stuck at how to implement this in actual codes.
我对Math的理解不是很好,定义的循环结构确实会有所帮助.
I'm not really very good with Math, A defined loop structure would really help.
非常感谢!
推荐答案
这里是一种从整数列表中获取所有可能总和的方法:
Here is a method that gets all possible sums from a List of Integers:
public static void getAllPermutations(final List<Integer> data,
final Set<Integer> holder){
if(data.isEmpty()){
return;
}
final Integer first = data.get(0);
if(data.size() > 1){
getAllPermutations(data.subList(1, data.size()), holder);
for(final Integer item : new ArrayList<Integer>(holder)){
holder.add(first.intValue() + item.intValue());
}
}
holder.add(first);
}
用法:
List<Integer> data = Arrays.asList(1, 2, 3, 4, 5, 6);
Set<Integer> permutations = new TreeSet<Integer>();
getAllPermutations(data, permutations);
System.out.println(permutations);
输出:
[1、2、3、4、5、6、7、8、9、10、11、12、13、14、15、16、17、18、19、20、21]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
虽然此解决方案不会为您提供导致求和的操作数,但它将包括从1
到1 + 2 + 3 + 4 + 5 + 6
这篇关于卡在组合问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!