是的,这很好用。如果你想枚举所有的 n 卡组合,这是行不通的。
为此,您需要递归。将卡片 0 放入插槽 0。递归枚举剩余 n-1 个插槽中的所有 n-1 手牌(不包括 0)。重复,卡 1 在插槽 0。很容易。
编辑:一些代码:
private static final int NUM_CARDS = 52;
public static void main(String[] args) {
enumerateAllHands(Integer.parseInt(args[0]));
}
private static void enumerateAllHands(int n) {
if (n > NUM_CARDS) {
throw new IllegalArgumentException();
}
int[] cards = new int[n];
BitSet cardsUsed = new BitSet();
enumerate(cards, 0, cardsUsed);
}
private static void enumerate(int[] cards, int from, BitSet cardsUsed) {
if (from == cards.length) {
emit(cards);
} else {
for (int i = 0; i < NUM_CARDS; i++) {
if (!cardsUsed.get(i)) {
cards[from] = i;
cardsUsed.set(i);
enumerate(cards, from + 1, cardsUsed);
cardsUsed.clear(i);
}
}
}
}
private static void emit(int[] cards) {
System.out.println(Arrays.toString(cards));
}