首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数组中的字符与java中的公式nPr的组合

数组中的字符与java中的公式nPr的组合
EN

Stack Overflow用户
提问于 2012-04-22 14:01:54
回答 2查看 1.6K关注 0票数 0

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

或者任何链接,如果这个问题在网上有解决方案的话。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-22 14:38:40

下面是一个通用的实现:

代码语言:javascript
复制
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;
}

像这样使用它:

代码语言:javascript
复制
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

票数 1
EN

Stack Overflow用户

发布于 2012-04-22 14:29:59

根据您的示例,我将打印组合:

代码语言:javascript
复制
public class PrintCombinations {

    public static void main( final String[] args ) {
        // testing input 1
        int n = 2;
        char[] a = { 'a', 'b', 'v', 'f' };
        solve( n, a );

        // testing input 2
        n = 3;
        a = new char[] { '1', '2', '3', '4', '5' };
        solve( n, a );

    }

    private static void solve( final int n, final char[] a ) {
        final int[] selected = new int[n];
        print( n, a, 0, selected );
    }

    // need to know how many items are selected - n, input array - a
    // item which can be selected next - from and already selected items
    private static void print( final int n, final char[] a, final int from, final int[] selected ) {
        if ( n == 0 ) { // all selected, just print them
            for ( int i = 0; i < selected.length; ++i ) {
                System.out.print( a[ selected[ i ] ] + " " );
            }
            System.out.println();
            return;
        }
        // select one and use recursion for others
        for ( int i = from; i < a.length; ++i ) {
            selected[ selected.length - n ] = i;
            print( n - 1, a, i + 1, selected );
        }
    }
}

但你必须意识到,组合的数量是

,所以这是一个很大的数字。

打印出1000万个数组需要一段时间...

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10265618

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档