我有一个算法可以解决您的问题,但您必须根据自己的需要对其进行调整。
不幸的是,我不知道它是否属于任何特定的已知数据结构。
简而言之,我会说它将您的数组转换为二进制位置并在其上循环,从没有标记任何项目的位置到标记所有项目的位置。
- 数组大小 = 6
- 初始标记数组 = "000000" // 6 个位置未标记
- 最终标记数组 = "111111" // 标记 6 个位置
递增二进制数组,它只对标记的位置求和。我们将能够总结所有可能的组合。
测试 1
给定你的参数:
- 总和 = 12
- 数组 = {1, 3, 4, 5, 5, 6}
结果是:
Position: 011010 // means the sum of item in position 1,2,4 (3 + 4 + 5 = 12)
Position: 011100 // means the sum of item in position 1,2,3 (3 + 4 + 5 = 12)
Position: 100011 // means the sum of item in position 0,4,5 (1 + 5 + 6 = 12)
Position: 100101 // means the sum of item in position 0,3,5 (1 + 5 + 6 = 12)
测试 2
给定你的参数:
- 总和 = 12
- 数组 = {1, 1, 1, 1, 2, 6}
结果是:
Position: 111111 // means the sum of item in position 0,1,2,3,4,5 (1+1+1+1+2+6 = 12)
代码可能会有所改进,但如下所示,在要求和的位置上简单地打印“1”,得到所需的数字。
public class Algorithm {
public static void main(String[] args) {
Algorithm checkSum = new Algorithm();
Integer[] array = {1, 3, 4, 5, 5, 6};
Integer sum = 12;
checkSum.find(array, sum);
System.out.println("------------------");
Integer[] array2 = {1, 1, 1, 1, 2, 6};
Integer sum2 = 12;
checkSum.find(array2, sum2);
}
private void find(Integer[] array, Integer sum) {
// This could be replaced by a StringUtils lib to fill with "1" the size of the array
String maxBinary = "";
for (int i=0; i<array.length; i++) {
maxBinary += "1";
}
int maxDecimal = Integer.parseInt(maxBinary, 2);
// This will iterate from "000000" to "111111"
for (int i=0; i<=maxDecimal; i++) {
String binaryNumber = lpad(Integer.toBinaryString(i), array.length);
int checkSum = 0;
for (int j=0; j<binaryNumber.length(); j++) {
if ("1".equals(binaryNumber.substring(j,j+1))) {
checkSum += array[j];
}
}
// This is the check to see if the sum is the desired one
if (sum == checkSum) {
System.out.println("Positions: " + binaryNumber);
}
}
}
/**
* This is a simple LPAD function to add zeros to the left of the string.
*/
private String lpad(String text, Integer size) {
String regex = "%0"+ size + "d";
return String.format(regex, Integer.parseInt(text));
}
}
希望对你有帮助!