您可以使用称为backtracking 的算法技术。
或者,根据你有多少玩家,你可以使用蛮力然后循环。例如,您可以使用以下命令来选择 2 个前锋和 1 个中锋的所有组合(这是一个 C++ 示例,只是为了说明该技术)。
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector< string > centers;
vector< string > forwards;
centers.push_back("joey");
centers.push_back("rick");
centers.push_back("sam");
forwards.push_back("steve");
forwards.push_back("joe");
forwards.push_back("harry");
forwards.push_back("william");
for(int i = 0; i < centers.size(); ++i) {
for(int j = 0; j < forwards.size(); ++j) {
for(int k = j+1; k < forwards.size(); ++k) {
printf("%s %s %s\n",centers[i].c_str(), forwards[j].c_str(), forwards[k].c_str());
}
}
}
return 0;
}
输出:
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
joey steve joe
joey steve harry
joey steve william
joey joe harry
joey joe william
joey harry william
rick steve joe
rick steve harry
rick steve william
rick joe harry
rick joe william
rick harry william
sam steve joe
sam steve harry
sam steve william
sam joe harry
sam joe william
sam harry william
> Terminated with exit code 0.
但是,重要的是要记住,如果您有很多玩家,那么您所做的任何事情都是“蛮力”,其中包括回溯(回溯与我上面使用的循环相同,只是它使用递归)是运行时间将呈指数增长。所以以5人阵容为例,如果你有10个中锋、20个前锋和18个后卫,那么运行时间基本上是:
10 * 20 * 20 * 18 * 18 = 1,296,000
(20 * 20 因为我们需要 2 个前锋,18 * 18 因为我们需要 2 个守卫)。
1,296,000 对运行时间来说并不算太糟糕,但是当你开始谈论 9 人名单时,你会得到更长的运行时间,因为现在你要处理更多的组合。
所以这取决于你有多少数据来判断这是否可行。