不使用遞迴求全排列和組合數

2021-09-23 21:02:26 字數 1136 閱讀 5708

同學遇到的面試問題,大意是m臺機器放在n個房間,不使用遞迴求列印所有情況

解題思路:情況共計n**m種。開始想將所有情況放入陣列,填充好陣列再逐個列印。隨後發現按照填充的思路,不使用大陣列也可以實現。思路是加入m=n=3,則27種情況,記i0...i26。0...m個數,0放入i0[0],i1[1],i2[2],i3[0],i4[1],i5[2]...,1放入i0[,i1,i2,

房間0房間1

房間20 1 2

1 20

1 20

0 21

20 121

00 212

0120 1

0 12

10 212

001 20 1 2

1 2002

10 212

0 1

/*  

* 非遞迴列印全排列。

*/

public class permutations

static void fullpermutation(char s)

} }

public static void main(string args)

}

類似的問題非遞迴列印組合數。例如cmn。建立長度為m的陣列,前n個置為1。從左到右掃瞄陣列元素值的10組合,找到第乙個10組合後將其變為01並將其左邊的1移動到最左端。

/* 

* 非遞迴列印組合數

*/

public class combinations

static void print(char s, int t)

system.out.println();

} public static void combinations(char s, int n)

} print(s, t);

break;

} }

if (i == m)

} }

public static void main(string args)

}

C STL求全排列和組合

c 11 stl內建了求全排列的模板函式next permutation和prev permutation,屬於標頭檔案和std命名空間,使用非常方便。例如 vector a while next permutation a.begin a.end for int i 0 i a.size 2 i ...

組合數和排列數

輸出組合數和排列數 include typedef long long ll ll factorial int num void cp mn int m,int n,ll a intmain 計算組合數 題目描述 計算組合數。c n,m 表示從n個數中選擇m個的組合數。計算公式如下 c n,m c ...

組合數學 容斥原理和錯位排列

真的,學了組合數學你會克服公式恐懼症0.0深有體會 設a 1,a2 a n 為有限集合,用 a i 表示集合ai 中的元素個數那麼有這樣的結論 a 1 a2 a n i 1n ai 1 in ai aj 1 i jn ai aj ak 1 n 1 a1 a2 an 總的概括就是奇數個集合的並集累加和...