編程排列組合工具類

/**  

* <p>Title: Ctest.java</p>  
* <p>Description: </p>  
* <p>Copyright: Copyright (c) 2017</p>  
* <p>Company: inca</p>  
* @author yudexiao  
* @date 2020年3月4日  
* @version 1.0  

*/  
package day09;

import java.util.Arrays;

/**
 * @author Yudx
 * @date 2020年3月4日 下午4:45:29
 */
public class CombiningUtil {
    /**
     * 計算階乘數,即n! = n * (n-1) * ... * 2 * 1 
     */
    private static long factorial(int n) {
        long sum = 1;
        while( n > 0 ) {
            sum = sum * n--;
        }
        return sum;
    }
    
    
    /**
     * 組合計算公式 C(m,n) = n! / (m! * (n - m)!)
     */
    public static long combination(int m, int n) {
        return m <= n ? factorial(n) / (factorial(m) * factorial((n - m))) : 0;
    }
    /**
     * 組合選擇(從列表中選擇n個組合)
     * @param dataList 待選列表
     * @param n 選擇個數
     */
    public static void combinationSelect(String[] dataList, int n) {
        System.out.println(String.format("C(%d, %d) = %d", 
                dataList.length, n, combination(dataList.length, n)));
        combinationSelect(dataList, 0, new String[n], 0);
    }
 
    /**
     * 組合選擇
     * @param dataList 待選列表
     * @param dataIndex 待選開始索引
     * @param resultList 前面(resultIndex-1)個的組合結果
     * @param resultIndex 選擇索引,從0開始
     */
    private static void combinationSelect(String[] dataList, int dataIndex, String[] resultList, int resultIndex) {  
        int resultLen = resultList.length;
        int resultCount = resultIndex + 1;
        if (resultCount > resultLen) { // 全部選擇完時,輸出組合結果
            System.out.println(Arrays.asList(resultList));
            return;
        }
 
        // 遞歸選擇下一個
        for (int i = dataIndex; i < dataList.length + resultCount - resultLen; i++) {
            resultList[resultIndex] = dataList[i];
            combinationSelect(dataList, i + 1, resultList, resultIndex + 1);
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章