日期:2014-05-20  浏览次数:20842 次

简单编程题,一时想不出了。
求一串字母A   B   C   D取n的所有组合,   如:
当n=2时为:
AB   AC   AD   BC   BD   CD
有精练代码的,马上给分。

------解决方案--------------------
又是排列组合,给你写一个的sample,关键是combine方法

import java.util.Arrays;
import java.util.Vector;


public class Combine {
public static void main(String[] args) {
try {
String[] a = { "A ", "B ", "C ", "D "};
String[][] result = combine(a, 2);
for (int i=0; i <result.length; i++) {
for (int j=0; j <result[i].length-1; j++) {
System.out.print(result[i][j]);
}
System.out.println(result[i][result[i].length-1]);
}

} catch (Throwable e) {
e.printStackTrace();
}
}

private static String[][] combine(String[] src, int n) {
if (src.length < n) {
return new String[0][0];
}

if (n == 1) {
String[][] result = new String[src.length][1];
for (int i=0; i <src.length; i++) {
result[i][0] = src[i];
}
return result;
}

if (src.length == n) {
String[][] result = new String[1][src.length];
for (int i=0; i <src.length; i++) {
result[0][i] = src[i];
}
return result;
}

Vector v = new Vector();
for (int i=0; i <src.length-1; i++) {
String[] sub = new int[src.length-i-1];
System.arraycopy(src, i+1, sub, 0, src.length-i-1);
if (sub.length < n-1) {
break;
}
String[][] tmp = combine(sub, n-1, sort);
for (int j=0; j <tmp.length; j++) {
String[] tmp2 = new String[n];
System.arraycopy(tmp[j], 0, tmp2, 1, n-1);
tmp2[0] = src[i];
v.add(tmp2);
}
}

String[][] result = new String[v.size()][n];
System.arraycopy(v.toArray(), 0, result, 0, v.size());
return result;
}
}