代码示例


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());
        }
    }
}