Java工具集-從N個元素裏面取M個指定長度的組合列表

代碼示例


import java.util.ArrayList;
import java.util.List;

/**
 * @program: simple_tools
 * @description: 從N個元素裏面取M個指定長度的組合列表
 * @author: Mr.chen
 * @create: 2020-06-08 17:24
 **/
public class CombinationUtil {

    public static <T> List<List<T>> combiantion(T[] datas, int number) {
        if ((datas == null) || (datas.length == 0) || (datas.length < number)) {
            return null;
        }
        List<List<T>> combines = new ArrayList<List<T>>();
        List<T> temps = new ArrayList<T>();

        combine(datas, 0, number, temps, combines);
        return combines;
    }

    public static <T> void combine(T[] datas, int begin, int number, List<T> temps, List<List<T>> combines) {
        if (number == 0) {
            List<T> aCombine = new ArrayList<T>();
            aCombine.addAll(temps);
            combines.add(aCombine);
            return;
        }
        if (begin == datas.length) {
            return;
        }
        temps.add(datas[begin]);
        combine(datas, begin + 1, number - 1, temps, combines);
        temps.remove(datas[begin]);
        combine(datas, begin + 1, number, temps, combines);
    }

    public static void main(String args[]) {
        Character chs[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
        List<List<Character>> combines = combiantion(chs, 3);
        for (List<Character> data : combines) {
            System.out.println(data.toString());
        }
    }
}

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