【发布时间】:2015-01-22 08:10:28
【问题描述】:
我有一张叫做手牌的列表
Arraylist<Card> hand = new Arraylist<Card>();
hand.add(new Card("As"));
hand.add(new Card("9h"));
...
手牌上限为五张。 我需要通过选择每三张手牌而不重复来获得手中的所有组合,并且顺序并不重要。
例子:
["Ac","10k","5c","7h","3h"]
结果:
[Ac,10k,5c]
[Ac,10k,7h]
[Ac,10k,3h]
[Ac, 5c, 7h]
[Ac, 5c, 3h]
[Ac, 7h, 3h]
[10k, 5c, 7h]
[10k, 5c, 3h]
[10k, 7h, 3h]
[5c, 7h, 3h]
编辑:我确实找到了一个与此相关的已回答问题。
Algorithm to return all combinations of k elements from n
这是java中的一个例子,我稍微调整了一下
public static void main(String[] args){
Card[] arr = { new Card(16), new Card(4), new Card(22), new Card(16), new Card(11) };
combinations(arr, 3, 0, new Card[3]);
}
static void combinations(Card[] arr, int len, int startPosition, Card[] result){
if (len == 0){
String str = "";
for(Card card : result)
{
str += card.CardString() + ", ";
}
System.out.println(str);
return;
}
for (int i = startPosition; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
combinations(arr, len-1, i+1, result);
}
}
【问题讨论】:
-
您尝试过什么?你做过研究吗,我有一种直觉,这个问题以前已经解决了……看看所有“相关”的问题
-
在您的示例中,您手中没有 5 张牌...
-
我建议拿笔写下所有可能的排列,同时使用列表索引而不是卡片名称。然后你可以弄清楚如何迭代列表索引。
-
也许你可以在这里找到一些想法:stackoverflow.com/questions/13215593/…
标签: java combinations