C C 用遞迴實現排列組合

2021-10-10 07:56:46 字數 2029 閱讀 7665

// 排列組合.cpp

#include

#define maxn 1000

#define maxm 1000

using

namespace std;

int n, m, a[maxn]

;// a為輸入的原始陣列

int cnt_c, cnt_p, cnt_a;

// 分別計數:組合情況,全排列情況,排列組合情況

bool is_a;

// 是否進行排列組合

void

print

(int array,

int n)

全排列函式:p(n)

// 全排列函式 p(n) - 將 n個元素全排列

// 主函式裡呼叫 perm(a, 1, n)

// permutation

void

perm

(int aa,

int l,

int r)

cnt_p++

;print

(aa, n)

;return;}

// 將第 i個元素與第 l個交換,進行遞迴

for(

int i = l; i <= r; i++

)}

組合函式:c(n,m)

// 組合函式:c(n, m) - 從 n個裡面取 m個

// 主函式裡呼叫:com(m, 1, n)

int com[maxm]

, tail =0;

// combination

void

com(

int m,

int l,

int r)

cnt_c++

;print

(com, m)

;return;}

// i從 l開始往後列舉

for(

int i = l; i <= r; i++

)}

主函式 main()

int

main()

輸入:

431

234

輸出:

431

234combination:12

3124

1342

34situations:

4permutation:12

3412

4313

2413

4214

3214

2321

3421

4323

1423

4124

3124

1332

1432

4131

2431

4234

1234

2142

3142

1343

2143

1241

3241

23situations:

24com & perm:12

3132

2132

3132

1312

1241

4221

4241

4214

1213

4143

3143

4143

1413

2342

4332

4342

4324

23situations:

24--

----

----

----

----

----

----

----

--process exited after 4.408 seconds with return value 0

請按任意鍵繼續.

..

C C 排列組合問題(遞迴)

1 問題描述 乙個mxn的矩形,從左下角走到右上角有多少種走法。include include using namespace std void luxian int alen,int blen,char p 100 int ai,int bi,int num const int alen 5 co...

遞迴實現排列組合

置換 給定n大於等於1個元素的集合,列印這個集合所有可能的置換。我們通過觀察集合,得到生成所有置換的簡單演算法,以下是演算法的構造過程 1 a跟在 b,c,d 的所有置換之後。2 b跟在 a,c,d 的所有置換之後。3 c跟在 a,b,d 的所有置換之後。4 d跟在 a,b,c 的所有置換之後。in...

遞迴實現排列組合問題

臨近acm大賽了,博主正在複習遞迴,畢竟博主是乙個菜鳥,對遞迴總是有太多的疑問,所以蒐羅了一些資料集中細談一下用遞迴處理的排列組合問題 題目 用遞迴演算法輸出cn m 從m中取n個數 的每一次的值 如下 include using namespace std int n,m,n n,m為題中的n,m...