一种从n个数字选出m个数字的组合,算法如下:
public class MathCombine { /** * @param args */ public static void main(String[] args) { int array[]={11,22,33,44,55}; int [][] ret=getCombine(array.length,3); if(null!=ret) { System.out.println("组合顺序如下:"); for (int j = 0; j < ret.length; j++) { for (int j2 = 0; j2 < ret[j].length; j2++) { System.out.print("["+(j2+1)+"]="+(ret[j][j2]+1)+";"); } System.out.print("\n"); } System.out.println("\n组合结果如下:"); for (int j = 0; j < ret.length; j++) { System.out.print("{"); for (int j2 = 0; j2 < ret[j].length; j2++) { System.out.print(array[ret[j][j2]]+((j2==ret[j].length-1)?"":",")); } System.out.print("}\n"); } } } /** * 从array 中选取 selectCount个 数字促成的组合,要求组合不重复 * @param array * @param selectCount */ public static int[][] getCombine(int n, int m) { if(m <=0 || m>n) { return null; } else { int count=getallCombineCount(n,m); int [][] ret=new int[count][m]; int index=0; int []indexArray=new int[m]; for (int i = 0; i < indexArray.length; i++) { indexArray[i]=i; ret[index][i]=i; } boolean isBreak=false; while(!isBreak) { for (int i = m-1; i >= 0; i--) { int nextValue = indexArray[i] + 1; if(nextValue > n-(m-i)) { if(i-1>= 0) { int preValue=indexArray[i-1]+1; if(preValue>n-(m-i)-1) { continue; } else { indexArray[i-1]=preValue; for (int j = i; j < m; j++) { if (j == m-1 ) { indexArray[j]=indexArray[j-1]; } else { indexArray[j]=indexArray[j-1]+1; } } break; } } else { isBreak=true; break; } } else//满足条件 { indexArray[i]=nextValue; index++; for (int j = 0; j < indexArray.length; j++) { ret[index][j]=indexArray[j]; } break; } } if(index>=count-1) { isBreak=true; } } return ret; } } /** * 获取组合总数 * @param n * @param m * @return */ public static int getallCombineCount(int n, int m) { return getAllCount(n,m)/getFactorial(m); } public static int getAllCount(int n,int m) { int ret=1; for (int i = 0; i < m; i++) { ret*=n; n--; } return ret; } public static int getFactorial(int m) { return m*(m>1?getFactorial(m-1):1); } }
输出结果如下:
时间: 2024-10-25 09:18:30