这段代码是一个简单的递归函数实现的字符串排列(permutation)程序。它使用了一个静态数组 `A` 来记录字符是否已经被使用过,以及一个静态数组 `result` 来存储排列的结果。
#include <iostream>
using namespace std;
// 函数perm用于生成字符串str的所有排列
void perm(char str[], int k) {
// 假设str长度小于9,A数组用于标记字符是否已经被使用
static int A[10] = {};
// result数组用于存储当前排列的结果
static char result[10];
// 如果str[k]不是字符串的结束符,说明还有字符可以排列
if (str[k] != '\0') {
// 遍历字符串str中的每个字符
for (int i = 0; str[i] != '\0'; i++) {
// 如果字符str[i]还没有被使用过(A[i]为0)
if (A[i] == 0) {
// 标记字符str[i]为已使用
A[i] = 1;
// 将当前字符添加到结果字符串的相应位置
result[k] = str[i];
// 递归调用perm函数,继续排列剩余的字符
perm(str, k + 1);
// 重置A[i]为0,以便字符可以再次使用
A[i] = 0;
}
}
} else {
// 当str[k]是字符串的结束符时,表示当前排列完成
result[k] = '\0'; // 将result[k]设置为结束符
// 打印当前排列的结果
cout << result << endl;
}
}
int main() {
// 定义一个字符串,注意长度不能超过9
char str[] = "ABCDEF";
// 调用perm函数,开始排列
perm(str, 0);
return 0;
}
#include <iostream>
using namespace std;
//permutation
void perm(char str[], int k) {
//假设str长度小于9
static int A[10] = {};
static char result[10];
if (str[k] != '\0') {
for (int i = 0; str[i] != '\0'; i++) {
if (A[i] == 0) {
A[i] = 1;
result[k] = str[i];
perm(str, k + 1);
A[i] = 0;
}
}
}
else {
result[k] = '\0';
cout << result << endl;
}
}
int main()
{
char str[] = "ABCDEF";
perm(str, 0);
}