问题
I want java implementation of generating nCr combinations of given set. e.g if set is {"java","php",".net","python"} program should return all possible nCr sets of given set.
回答1:
Adapting Gosper's hack, this works up to n = 64.
List<String> inputs;
List<List<String>> ncr = new ArrayList<List<String>>();
for (long x = (1 << r) - 1; (x >>> r) == 0;) {
// x contains a 1 bit for each input we should choose;
// iterate over the 1 bits of x
long y = x;
List<String> combination = new ArrayList<String>();
for (int i = Long.numberOfTrailingZeros(y);
y != 0; i = Long.numberOfTrailingZeros(y)) {
combination.add(inputs.get(i));
y &= ~(1 << i);
}
long u = x & -x;
long v = u + x;
x = v + ((v ^ x) / u) >>> 2;
}
来源:https://stackoverflow.com/questions/11945682/generating-ncr-combinations-of-given-set-in-java