前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java工具集-从N个元素里面取M个指定长度的组合列表

Java工具集-从N个元素里面取M个指定长度的组合列表

作者头像
cwl_java
发布2020-06-10 10:07:30
8980
发布2020-06-10 10:07:30
举报
文章被收录于专栏:cwl_Javacwl_Java
代码示例
代码语言:javascript
复制
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());
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-06-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档