|
发表于 2023-11-11 15:41:18
|
显示全部楼层
这是一个典型的排列组合问题,可以使用C++的递归函数来解决。下面是一个示例代码:
- #include <iostream>
- using namespace std;
- // 定义颜色枚举类型
- enum Color { RED, BLUE, YELLOW, BLACK };
- // 输出所有排列的递归函数
- void printPermutations(Color c1, Color c2, Color c3) {
- static int count = 0;
- string colors[] = {"red", "blue", "yellow", "black"};
- cout << ++count << " " << colors[c1] << " " << colors[c2] << " " << colors[c3] << endl;
- }
- // 递归生成所有排列
- void generatePermutations(int depth, Color c1, Color c2, Color c3) {
- if (depth == 3) {
- printPermutations(c1, c2, c3);
- return;
- }
- for (int i = RED; i <= BLACK; i++) {
- if (i != c1 && i != c2 && i != c3) {
- switch (depth) {
- case 0: generatePermutations(depth + 1, (Color)i, c2, c3); break;
- case 1: generatePermutations(depth + 1, c1, (Color)i, c3); break;
- case 2: generatePermutations(depth + 1, c1, c2, (Color)i); break;
- }
- }
- }
- }
- int main() {
- generatePermutations(0, RED, RED, RED);
- return 0;
- }
复制代码
这段代码定义了一个枚举类型 Color 来表示颜色,然后使用递归函数 generatePermutations 来生成所有可能的排列,最后在 main 函数中调用 generatePermutations 函数开始生成排列。 |
|