递归实现排列组合

来源:互联网 发布:ubuntu ssh 编辑:程序博客网 时间:2024/05/18 03:14

(置换)给定n大于等于1个元素的集合,打印这个集合所有可能的置换。我们通过观察集合{a,b,c,d},得到生成所有置换的简单算法,以下是算法的构造过程:

(1)       a跟在(b,c,d)的所有置换之后。

(2)       b跟在(a,c,d)的所有置换之后。

(3)       c跟在(a,b,d)的所有置换之后。

(4)       d跟在(a,b,c)的所有置换之后。

 

#include <stdio.h>#include <stdlib.h>#define I 0#define N 2void SWAP(char *c1_,char *c2_,char temp){    temp=*c1_;    *c1_=*c2_;    *c2_=temp;}void perm(char *list,int i,int n){ //generate all the permutations of list[i] to list[n]);    int j,temp=0;    if(i==n){        for(j=0;j<=n;j++) printf("%c",list[j]);        printf("    ");    }    else{    //list[i] to list[n] has more than one permutation,generate these recursively        for(j=i;j<=n;j++){            SWAP(&list[i],&list[j],temp);            perm(list,i+1,n);            SWAP(&list[i],&list[j],temp);        }    }}int main(){    char list[3]={'a','b','c'};    perm(list,I,N);    system("pause");    return 1;}


原创粉丝点击