字符的递归排列生成器

recursive permutation generator for characters

本文关键字:排列 递归 字符      更新时间:2023-10-16

可能的重复项:
生成具有所有字符排列的字符串

我是 c++ 的初学者,我真的需要你的帮助。我正在做使用递归进行排列的程序。这是我的代码,但输出很奇怪,有相同的数字重复很多次和空格。我无法找出问题所在,或者可能需要添加更多内容。请帮助我。这是我的代码:

#include <iostream>
using namespace std;
#define swap(x,y,t)  ((t)=(x), (x)=(y), (y)=(t))
void perm(char *list, int i, int n);
int main(){
    char a[4]={'a','b','c'};
    perm(a,0,3);
    //cout<<a<<endl;    
    return 0;
}
void perm(char *list, int i, int n){
    int j, temp;
    if (i==n){
        for (j=0; j<=n; j++)
            printf("%c", list[j]);
        printf("     ");
    }
    else {
        for (j=i; j<=n; j++){
            swap(list[i],list[j],temp);
            perm(list,i+1,n);
            swap(list[i],list[j],temp);
            cout<<list<<endl;
        }
    }
}

该函数是正确的,但您没有正确调用它。

perm(a,0,3);

应该是

perm(a,0,2);

为什么?

您的 for 循环:

for (j=i; j<=n; j++){

直到n,所以n应该是一个有效的索引。

工作正常