2

我刚刚大脑受阻,我有一个 Deck 对象,并希望以迭代的方式从中获取每 5 张卡片组合。有人可以告诉我如何做到这一点,我想它会是:

for(int i =0; i <52; i++){
    for(int j = i + 1 ; j < 52; j++){
        for(int k = j + 1; k < 52; k++{ 
            for(int l = k + 1; l < 52; l++){
                for(int m = l + 1; m < 52; m++){
                }
             }
         }
     }
  }

它是否正确?

谢谢

4

1 回答 1

5

是的,这很好用。如果你想枚举所有的 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));
}
于 2010-03-05T14:30:57.583 回答