c語言中一種典型的排列組合演算法

來源:互聯網
上載者:User

標籤:lib   blog   cal   http   img   png   scan   images   swap   

c語言中的全排列演算法和組合數演算法在實際問題中應用非常之廣,但演算法有許許多多,而我個人認為方法不必記太多,最好只記熟一種即可,一招鮮亦可吃遍天

全排列:

#include<stdio.h>

void swap(int *p1,int *p2)

{

int t=*p1;

*p1=*p2;

*p2=t;

}

void permutation(int a[],int index,int size)

{

if(index==size)

{

for(int i=0;i<size;i++)

printf("%d ",a[i]);

printf("\n");

}

else

{

for(int j=index;j<size;j++)

{

swap(&a[j],&a[index]);

permutation(a,index+1,size);//此處用到遞迴思想

swap(&a[j],&a[index]);

}

}

}

int main()

{

int n;

scanf("%d",&n);

int a[n];

for(int i=0;i<n;i++)

a[i]=i+1;

permutation(a,0,n);

return 0;

}

 

 

組合:

#include<stdio.h>

void combine(int n,int m,int a[],int b[],const int M)

{

for(int j=n;j>=m;j--)

{

b[m-1]=j-1;

if(m>1)combine(j-1,m-1,a,b,M);//用到了遞迴思想

else

{

for(int i=M-1;i>=0;i--)printf("%d ",a[b[i]]);

printf("\n");

}

}

}

int main()

{

int n,m;

scanf("%d%d",&n,&m);

int a[n];int b[m];

for(int i=0;i<n;i++)

a[i]=i+1;

const int M=m;

combine(n,m,a,b,M);

}

c語言中一種典型的排列組合演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.