关于分治和递归的几点思考 有关全排序问题

来源:互联网 发布:月目标计算法 编辑:程序博客网 时间:2024/06/06 15:04

自己认为这就是permutation 的函数的内容:

对于全排序来讲{1,2,3,4}

1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 3 2
1 4 2 3
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 3 1
2 4 1 3
3 2 1 4
3 2 4 1
3 1 2 4
3 1 4 2
3 4 1 2
3 4 2 1
4 2 3 1
4 2 1 3
4 3 2 1
4 3 1 2
4 1 3 2
4 1 2 3

总共产生24种排列

用分治和递归的思想来解释这种问题

对于两个数来讲 直接交换位置就会出现两种情况

对于三个数来讲 将其中1个数提到最前面参考两个数的排序

对于四个数来讲 讲其中1个数提到最前面参考三个数的排序

------------------------------等等

#include<stdio.h>#include<iostream>#include<stdlib.h>using namespace std;int a[4]={1,2,3,4};void Perm(int beg,int end){      if(beg==end){           int i;           for(i=0;i<4;i++)              printf("%d ",a[i]);           printf("\n");                   }           for(int i=beg;i<=end;i++){            swap(a[i],a[beg]);      //将每一个数提到最前面         Perm(beg+1,end);         swap(a[i],a[beg]);      //复原                       }}int main(){    int beg,end;    while(scanf("%d%d",&beg,&end)!=EOF){  //输入0 3 就可产生全排序         Perm(beg,end);                                                                           }   }