题解 | #24点#
24点
http://www.nowcoder.com/questionTerminal/263fa05acac5424a91214694a1c1eb8f
首先需要求出所有的子集合
已知父集合长度为N可知子集合的数量 = 2^n = 1 << n
再通过 i & (1 << j)) > 0 判断父集合中的每一位是否匹配上 求出子集合
最终遍历子集合列表求出和为24的结果有多少个
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int size = in.nextInt();
List<Integer> numList = new ArrayList<>();
for (int i = 0; i < size; i++) {
int num = in.nextInt();
numList.add(num);
}
System.out.println(getResult(numList));
}
/**
* 获取符合24点的数量
* @param numList 待计算集合
* @return 符合24点的数量
*/
public static int getResult(List<Integer> numList) {
Set<List<Integer>> listSonList = getListSon(numList);
int count = 0;
for (List<Integer> numSonList : listSonList) {
int sum = 0;
for (Integer num : numSonList) {
sum += num;
}
if (sum == 24) {
// System.out.println(numSonList);
count++;
}
}
return count;
}
/**
* 获取 所有 子集合
* 可知子集合总数为 2^n == 1 << n
* @param numList 父集合
* @return 子集合Set
*/
public static Set<List<Integer>> getListSon(List<Integer> numList) {
int n = numList.size();
Set<List<Integer>> listSonList = new HashSet<>();
for (int i = 0; i < 1 << n; i++) {
List<Integer> listSon = new ArrayList<>();
for (int j = 0; j < n; j++) {
// 分别判断集合每一位是否与二进制位匹配上
if ((i & (1 << j)) > 0) {
listSon.add(numList.get(j));
}
}
Collections.sort(listSon);
listSonList.add(listSon);
}
return listSonList;
}
}

