求从n个不重复数中取出m个数的所有组合(排列):
private static LinkedList<Integer> result = new LinkedList<Integer>();
private static long resultCount = 0;
private static void combine(int[] source, int m, int start) {
if (result.size() == m) {
resultCount++;
printResult(result);
return;
}
for (int i = start; i < source.length; i++) {
result.add(source[i]);
combine(source, m, i + 1);
result.removeLast();
}
}
private static void permutate(int[] source, int m) {
if (result.size() == m) {
resultCount++;
printResult(result);
return;
}
for (int i = 0; i < source.length; i++) {
if (result.contains(source[i])) {
continue;
}
result.add(source[i]);
permutate(source, m);
result.removeLast();
}
}
private static void printResult(List<Integer> result) {
Iterator<Integer> it = result.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
}
调用代码
int[] source = new int[10];
for (int i = 0; i < source.length; i++) {
source[i] = i + 1;
}
combine(source, 6, 0);
//permutate(source, 2);
System.out.println("total number is " + resultCount);
posted on 2009-09-13 22:29
Sam Zheng 阅读(387)
评论(0) 编辑 收藏