用二进制的方法,
public static ArrayList<ArrayList<Integer>> generateCombinations(Array
List <Integer> array) {
ArrayList<ArrayList<Integer>> combinations = new
ArrayList<>();
int n = array.size();
int max = (1 << n); // 2^n
for (int i = 1; i < max; i++) {
ArrayList<Integer> combination = new ArrayList<>();
for (int j = 0; j < n; j++) {
if ((i & (1 << j)) != 0) {
combination.add(array.get(j));
}
}
combinations.add(combination);
}
return combinations;
}
【 在 iStudy 的大作中提到: 】
: a,b,c,d四个对象
: 我要生成a,b,c,d的全组合===C(4,1)+C(4,2)+C(4,3)+C(4,4)
: 结果就是输出 {a,b,c,d, ab,ac,ad,bc,bd,cd,abc,abd,acd,bcd,abcd}
: ...................
--
FROM 119.139.196.*