N个字母的全排列

//N个字母的全排列
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
char output[SIZE]={};//全排列以后的数组
char data[SIZE]={'A','B','C','D','E'};//原数据数组
int count;//用于显示全排列的组数

/* 函数名: issafe
*  函数功能:判断接下来要存入的数据是否出现过
*  入口参数:1.step  已经放过step个数,从0到step-1
             2.value 当前要放入的值 
*  返回值: bool变量,出现过返回0,没有出现过返回1
*/
bool issafe(int step,int value){
    bool ret = true;
    for(int i=0;i<step;i++){
        if(output[i]==value)
            ret = false;
    }
    return ret;
}


/* 函数名:all_sort
*  函数功能:把N个字母全排列
*  入口参数:step 当前排序的位置
*  返回值:空
*/
void all_sort(int step){
    if(step == SIZE){
    for(int i=0;i<SIZE;i++){
        printf("%c",output[i]);}
    printf("
");
    count++;
    return;
    }

    for(int j=0;j<SIZE;j++){
       if(issafe(step,data[j])){
           output[step] = data[j];
           all_sort(step+1);
       }
     }
}
int main(){
    all_sort(0);
    printf("%d
",count);
    system("pause");


}


可以使用:

freopen("output.txt","w",stdout);

//把输出结果重定向到文件

结果出现问题的思路:

1.在迭代过程的每一步处理的过程中的数组下标写错了。出现的错误:output[step] =data[i];

错写成output[i] = data[i];

2.在判断是否安全的函数中数组下标写错了。出现的错误:if(value == output[j])错写成if(value==data[j]) 比较的逻辑错误了。

仔细检查数组下标和迭代的思路进行比较。

大多数想法要么平庸,要么更糟糕,这很大程度上因为绝妙的想法难得一见,而且他们还要在我们身边这个充斥了各种恶俗的所谓常识的环境中孕育生长。
原文地址:https://www.cnblogs.com/linux0537/p/6089961.html