组合算法(类似C(5,2))
Posted zhchy89
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了组合算法(类似C(5,2))相关的知识,希望对你有一定的参考价值。
/**
* get combinations ( C(superscript, subscript) )
* @param totalCount normal data node group count except primary data node group
* @param selectCount secondary data node count
* @return the possibility of combinations
* e.g. the possibility of select 2 members from 5 members
* the possibility: {[5,4], [5,3], [5,2], [5,1], [4,3], [4,2], [4,1], [3,2], [3,1], [2,1]}
*/
private List<Deque<Integer>> getCombination(int totalCount, int selectCount){
//The combination of secondary count from group Count which expect primary group .
int comb[] = new int[selectCount+1];
comb[0] = selectCount;
List<Deque<Integer>> resultIndexList = new ArrayList<>();
combination(comb, totalCount, selectCount, resultIndexList);
logger.info("secondary group index combination:{}", resultIndexList);
return resultIndexList;
}
/**
* get combinations( C(superscript, subscript) )
* e.g. C(5, 2) ,the resultList: {[5,4], [5,3], [5,2], [5,1], [4,3], [4,2], [4,1], [3,2], [3,1], [2,1]}
* @param comb last result of combination
* @param superscript max of the number
* @param subscript select numbers count
* @param resultList result after combination
*/
private void combination(int comb[], int superscript, int subscript, List<Deque<Integer>> resultList) {
for (int i = superscript; i >= subscript; i--) {
// select current head element
comb[subscript] = i;
if (subscript > 1) {
// enter next smaller combination
combination(comb, i-1, subscript-1, resultList);
} else {
Deque<Integer> selectIndexQueue = new ArrayDeque<>();
// save combination
for (int j=comb[0]; j>0; j--) {
selectIndexQueue.add(comb[j]);
}
resultList.add(selectIndexQueue);
}
}
return;
}
以上是关于组合算法(类似C(5,2))的主要内容,如果未能解决你的问题,请参考以下文章