有人可以告诉我如何使用公式 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/