java - java中用公式nPr组合数组中的字符

标签 java arrays combinations npr

有人可以告诉我如何使用公式 nPr 实现存储在数组中的字符值的组合吗? 例如,如果我有一组 {a,b,v,f} 并且我想一次选择 2 个,则答案应该是 {a,b} {a,v} {a,f} {b,v} {b,f} {v,f}。

或者任何链接(如果该问题在网络上有解决方案)。 谢谢。

最佳答案

这是一个一般实现:

static <T> List<List<T>> combinations( List<T> list, int n ){

    List<List<T>> result;

    if( list.size() <= n ){

        result = new ArrayList<List<T>>();
        result.add( new ArrayList<T>(list) );

    }else if( n <= 0 ){

        result = new ArrayList<List<T>>();
        result.add( new ArrayList<T>() );

    }else{

        List<T> sublist = list.subList( 1, list.size() );

        result = combinations( sublist, n );

        for( List<T> alist : combinations( sublist, n-1 ) ){
            List<T> thelist = new ArrayList<T>( alist );
            thelist.add( list.get(0) );
            result.add( thelist );
        }
    }

    return result;
}

像这样使用它:

List<Character> list = new ArrayList<Character>();
list.add('a');
list.add('b');
list.add('c');
list.add('d');

List<List<Character>> combos = combinations( list, 2 );

这是一个ideone .

关于java - java中用公式nPr组合数组中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10265618/

相关文章:

java - 将时间间隔添加到给定时间字符串

java - 是否有用于在 Eclipse 中为 Java 枚举生成 switch 语句的模板或其他东西?

c# - 找到最好的区间匹配结果

java - 卡夫卡 : Manually producing record triggers exception in consumer

java - 具有独特元素的有序集合并替换最旧的元素

c# - 如何在 C# 中将 null 数组反序列化为 null?

javascript - 查找总和为目标值的给定大小列表的子集

c++ - C++ 中的 vector 和结构

ruby - ruby 字符串中选定字符替换的所有可能组合

algorithm - 从列表中选择项目