Java打印无序全排列组合
程序员文章站
2022-06-07 20:10:16
...
指定 totalCount 和 numCount 后, 可以打印所有的排列组合
// 全排列下标
int allIndex = 0;
// 目标数组长度
private final int totalCount = 15;
// 选几个数
int numCount = 1;
// 存储所有的排列
private int[][] allSequence;
// 存储单个排列
private final int[] simple = new int[numCount];
@Test
public void test0831() {
// 初始化allSequence
double allSequenceCount = 1;
for (int i=0; i<numCount; i++) {
allSequenceCount = allSequenceCount * (totalCount-i) / (numCount-i);
}
allSequence = new int[(int)Math.round(allSequenceCount)][numCount];
allPossible(0, numCount);
}
/**
*
* @param index 上一层选取的数的下标
* @param count 这一层需要选几个数
*/
public void allPossible(int index, int count) {
for (int i=index; i<totalCount-count+1; i++) {
simple[numCount - count] = i;
if (count > 1) {
allPossible(i+1, count - 1);
} else {
for (int j=0; j<numCount; j++) {
allSequence[allIndex][j] = simple[j];
}
allIndex++;
}
}
}