其他分享
首页 > 其他分享> > C语言 全排列

C语言 全排列

作者:互联网

1.无重复字符

#include  <stdio.h>  
#include  <string.h>
#define N 30

void p(char a[], int m, int n)
{
    char b[N], t ;    
    int i ;    if (m == n)    
    printf("%s ", a) ;    
    else    
    for (i = m ; i < n ; i++)    
    {        
        strcpy(b, a) ;        
        t = a[m], a[m] = a[i], a[i] = t ;        
        p(a, m+1, n) ;        
        strcpy(a, b) ;    
    } 
}

main(void)
{
    char a[N] ;    
    printf("请输入一个没有重复字符的字符串:\n") ;    
    scanf("%s", a) ;    
    int m = 0, n = strlen(a) ;    
    p(a, m, n) ;
}

2.有重复字符

#include  <stdio.h>
#include  <string.h>
#define N 100

char result[N][N], x[N] ;
int count = 0 ; 

void into()
{
	int i ;     
	for (i = 0 ; i < count ; i++)	
	{		
	    if (strcmp(result[i], x) == 0)			
	    break ;		
	}     
	if (0 == count || i == count)     
	strcpy(result[count++], x) ;
}

void p(int m, int n)
{
    char t[N], temp ;    
    int i ;    
    if (m == n)    
    into() ;    
    else    
    for (i = m ; i < n ; i++)    
    {        
        strcpy(t, x) ;        
        temp = x[m], x[m] = x[i], x[i] = temp ;        
        p(m+1, n) ;        
        strcpy(x, t) ;    
    } 
}

main (void)
{
	printf("请输入一个字符串(有重复字符):\n") ;	
	gets(x) ;	
	p(0, strlen(x)) ;	
	for (int i = 0 ; i <= count ; i++)         
	printf("%s\n", result[i]) ;
}

标签:count,排列,int,void,C语言,char,strcpy,include
来源: https://blog.csdn.net/m0_63790435/article/details/122338610