本身是个所谓的玩笑题,然后采用刚了解的算法写个程序来计算,还是采用按位对应法,获取一个数组的所有长度为3的子序列,具体分析参见获取数组的所有子序列
@Test
public void add() {
int[] array = {1, 3, 5, 7, 9, 11, 13, 15};
int length = array.length;
int end = 1 << length;
int mark = 0;//标记
List<List<Integer>> result = new ArrayList<>();
for (mark = 0; mark < end; mark++) {
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < length; i++) {
if ((1 << i & mark) != 0) {//!=0存在 =0不存在
arrayList.add(array[i]);
}
}
//筛选3个的子集
if (arrayList.size() == 3) {
result.add(arrayList);
for (int i = 0; i < arrayList.size(); i++) {
System.out.print(arrayList.get(i) + ",");
}
System.out.println();
}
}
int count = 0;
for (int i = 0; i < result.size(); i++) {
List<Integer> integers = result.get(i);
int sum = 0;
for (int j = 0; j < integers.size(); j++) {
sum += integers.get(j);
}
if (sum == 30) {
count++;
}
}
System.out.print("数量:" + count);
}