ABC有多少种排列组合

package com.thinkgem.jeesite.test;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class PermutationsTest {

    public static void main(String[] args) {
        System.out.println(getSize(4));
        System.out.println(getDeduplicationList(Lists.newArrayList("A", "B", "D", "D")));
        System.out.println(getList(Lists.newArrayList("A", "B", "D", "D")));
    }

    /**
     * 去除重复的数据
     * @param list
     * @return
     */
    public static List> getDeduplicationList(List list) {
        List> listLists = getList(list);
        Map> stringListMap = listLists.parallelStream().collect(Collectors.toMap(keys -> {
            StringBuffer sb = new StringBuffer();
            keys.forEach(key -> {
                sb.append(key);
            });
            return sb.toString();
        }, value -> value, (v1, v2) -> v1));
        return Lists.newArrayList(stringListMap.values());
    }

    /**
     * 不进行去重,也就是list中每个字符都不相同
     *
     * @param list
     * @return
     */
    public static List> getList(List list) {
        List> listLists = Lists.newArrayList();
        for (int i = 0; i < list.size(); i++) {
            listLists = getSpecies(i + 1, listLists, list.get(i));
        }
        return listLists;
    }

    /**
     * 实现方式为前一次获取的组合List,取出前一次组合的每一个list信息,新增的值可以插入list索引位置0-len位,
     * 其余的值判断索引位置是否小于它占用的位置,小于不用管,大于的话,所有的位置都往后移一位
     *
     * @param len
     * @param listLists
     * @param value
     * @return
     */
    private static List> getSpecies(int len, List> listLists, String value) {
        if (len == 1) {
            List listList = Lists.newArrayList(value);
            listLists.add(listList);
            return listLists;
        }
        List> valueLists = Lists.newArrayList();
        for (List listList : listLists) {
            for (int i = 0, size = listList.size() + 1; i < size; i++) {
                String[] strings = new String[size];
                strings[i] = value;
                for (int j = 0; j < listList.size(); j++) {
                    if (j < i) {
                        strings[j] = listList.get(j);
                    } else {
                        strings[j + 1] = listList.get(j);
                    }
                }
                valueLists.add(Lists.newArrayList(strings));
            }
        }
        return valueLists;
    }

    /**
     * 获取数量 多一个参数等于在获取前一次list的基础上把单个list提出,
     * 当前值可以放在list的索引最大位置+1处,表现公式为:f(n)= n * f(n-1)
     *
     * @param len
     * @return
     */
    private static int getSize(int len) {
        if (len == 1) {
            return 1;
        }
        return len * getSize(len - 1);
    }
}

 

你可能感兴趣的:(java项目技术所遇问题总结)