组合算法(类似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;
}

猜你喜欢

转载自www.cnblogs.com/zhchy89/p/9216639.html