递归字符排列生成器

5
可能重复:
生成包含所有字符排列的字符串 我是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;
        }
    }
}

дҢ еЏҮд»ӨйЂљиү‡дҢүз”Ёе†…зҢ®дғҺ<algorithm>зљ„next_permutationе‡Ңж•°жқӨйЃүе…Қең€е¤љйғ»зѓ¦гЂ‚ - Raymond Chen
1个回答

1

这个函数是正确的,但你没有正确地调用它。

perm(a,0,3);

应该是

perm(a,0,2);

为什么?

你的for循环:

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

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

运行良好


非常感谢您的回复 ^^))) - bionian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接