轻松解决排列算法

    科技2025-10-08  3

    问题:

    求1 ,2,3,4的全排列 

    思路:利用递归解决这个问题

    1,2,3,4的全排列就等与 4+{2,3,1}的全排列 ,3+{2,1,4}的全排列,1+{2,3,4}的全排列

    void perm(int *a,int low,int high){ if(low==(high-1)){ for(int i=0;i<high;i++){ cout<<a[i]<<" "; } cout<<endl; return; } for(int i=low;i<high;i++){ swap(a[i],a[low]); perm(a,low+1,high); swap(a[i],a[low]); } } int main(){ int a[4]={1,2,3,4}; perm(a,0,4); return 0; }

     

    但是如何求呢?这个也简单,稍微改动一下上面的代码即可

    void perm(int *a,int low,int high){ // if(low==(high-1)){ int r =3; if(low== (r)){ for(int i=0;i<(r);i++){ cout<<a[i]<<" "; } cout<<endl; return; } for(int i=low;i<high;i++){ swap(a[i],a[low]); perm(a,low+1,high); swap(a[i],a[low]); } } int main(){ int a[4]={1,2,3,4}; perm(a,0,4); return 0; }

    我们这就轻松实现了任意数列的全排列及排列

    Processed: 0.009, SQL: 9