首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

求n个字符的全排列解决方案

2012-12-24 
求n个字符的全排列写死我了,终于写好了。#include stdio.h#include stdlib.h#include string.h#defin

求n个字符的全排列
写死我了,终于写好了。


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define debug(fmt,argv...) //printf("%s:%d "fmt"\n", __FUNCTION__, __LINE__, ##argv)
#define MAX 10

typedef struct node{
char c[MAX];
}Node, *pNode;


int test;
void em(pNode p, char* str, int layer);
int fact(int n);

int main(int argc, char** argv){
char *str;//no more than length MAX-1
pNode a;
int n,i;
int SIZE;

printf("input a string:\n");
scanf("%s",str);
n=strlen(str);
if(n>MAX-1){
printf("exit beacuase your string is more than %d\n",MAX-1);
return -1;
}
SIZE=fact(n);

if(!(a=(pNode)malloc(sizeof(Node)*SIZE))){
printf("mem alloc falied.\n");
return ;
}
debug("%d",2);
//emernuation
em(a,str,0);

//printf
for(i=0; i<SIZE;i++){
printf("%09d\t%s\n",i+1, a[i].c);
}


//free
if(a){
free(a);
}

return 0;
}

void em(pNode p, char* str, int layer){
int n = strlen(str);
char** rest;
pNode *q;
int i,j,k,f,section = fact(n-1);

if(n<2){
//assignment directly
p->c[layer] = str[0];
p->c[layer+1] = '\0';

return;
}

//mem allocation
if(!(q=(pNode *)malloc(sizeof(pNode)*n)) ||
   !(rest=(char **)malloc(sizeof(char *)*n)) ){
printf("mem alloc falied.\n");
return ;
}

for(i = 0; i < n; i++){
if(!(rest[i]=(char *)malloc(sizeof(char)*n))){
printf("mem alloc falied.\n");
return;
}
}

//loop, address each token in the string
for(i = 0; i < n; i++){
q[i] = p + i * section;
//the section to be addressed
for(j = 0; j < section; j++){
(p + i * section + j)->c[layer] = str[i];
debug("%d,%c", ++test, (p+i*section+j)->c[layer]);
}

//the next string to be adderssed
f=0;
for(k = 0; k < n; k++){
if(k!=i){
rest[i][f]=str[k];
f++;
}

}
rest[i][n-1]='\0';

//recursion
em(q[i],rest[i],layer+1);
}

//free
for(i=0;i<n;i++){
if(rest[i]){
free(rest[i]);
}
}

if(rest){
free(rest);
}

if(q){
free(q);
}
}

int fact(int n){

if (n==0 || n==1){
return 1;
}
else{
return n*fact(n-1);
}
}



[解决办法]
lz就是为了表示自己写好了,然后发了个贴?
[解决办法]
哦,散分贴么。。。。。。求分
[解决办法]
全排列  用递归啊

------解决方案--------------------



#include <stdio.h> 
inline void Swap(char& a, char& b) 
{// 交换a和b 
    char temp = a; 
    a = b; 
    b = temp; 


void Perm(char list[], int k, int m) 
{ //生成list [k:m ]的所有排列方式 
    int i; 
    if (k == m) {//输出一个排列方式 
        for (i = 0; i <= m; i++) 
            putchar(list[i]); 
        putchar('\n'); 
    } 
    else // list[k:m ]有多个排列方式 
        // 递归地产生这些排列方式 
        for (i=k; i <= m; i++) { 
            Swap (list[k], list[i]); 
            Perm (list, k+1, m); 
            Swap (list [k], list [i]); 
        } 


int main() 

    char s[]="123"; 
    Perm(s, 0, 2); 
    return 0; 



热点排行