yangzhixiaohuli 发表于 2023-11-11 15:41:11

求助一下

口袋里有红、蓝、黄、黑4种颜色的球若干,每次从口袋先后取出3个球,问得到3种不同颜色的球的可能取法,输出每种排列的情况。球只能是4种颜色之一,而且判断各球是否同色,可以用枚举类型变量处理。

输入格式:


输出格式:
输出所有排列。

输入样例:
在这里给出一组输入。例如:


输出样例:
在这里给出相应的输出。例如:

1 red blue yellow
2 red blue black
3 red yellow blue
4 red yellow black
5 red black blue
6 red black yellow
7 blue red yellow
8 blue red black
9 blue yellow red
10 blue yellow black
11 blue black red
12 blue black yellow
13 yellow red blue
14 yellow red black
15 yellow blue red
16 yellow blue black
17 yellow black red
18 yellow black blue
19 black red blue
20 black red yellow
21 black blue red
22 black blue yellow
23 black yellow red
24 black yellow blue

这题用C++怎么做

isdkz 发表于 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 << " " << colors << " " << colors << 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 函数开始生成排列。
页: [1]
查看完整版本: 求助一下