//package com.nowjava;
import java.util.ArrayList;
/**
来 自 时 代 Java - nowjava.com
**/
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] argv) throws Exception {
int n = 2;
boolean zeroBased = true;
System.out.println(listAllCombinations(n, zeroBased));
}
public static List<Set<Integer>> listAllCombinations(int n,
boolean zeroBased) {
List<Set<Integer>> allCombinations;
// 来自 时代Java - N o w J a v a . c o m
allCombinations = new ArrayList<Set<Integer>>();
for (int k = 0; k < n; k++) {
allCombinations.addAll(listCombinationsFixed2(n, k, zeroBased));
}
return allCombinations;
}
public static List<Set<Integer>> listCombinationsFixed2(final int n,
final int k, final boolean isZeroBased) {
List<Set<Integer>> combinations = new ArrayList<Set<Integer>>();
//System.out.println("will get combinations with (n,k)=(" + n + "," + k + ")");
Integer[] combination = null;
if (k == 0 || k == n) {
combination = new Integer[n];
for (int i = 0; i < n; i++) {
combination[i] = i;
}
} else {
combination = new Integer[k];
for (int i = 0; i < k; i++) {
combination[i] = i;
}
}
if (isZeroBased) {
combinations.add(new HashSet<Integer>(Arrays
.asList(combination)));
} else {
Integer[] tempCombination = new Integer[combination.length];
for (int i = 0; i < combination.length; i++) {
tempCombination[i] = combination[i] + 1;
}
combinations.add(new HashSet<Integer>(Arrays
.asList(tempCombination)));
}
while (nextCombination(combination, n, k)) {
if (isZeroBased) {
combinations.add(new HashSet<Integer>(Arrays
.asList(combination)));
} else {
Integer[] tempCombination = new Integer[combination.length];
for (int i = 0; i < combination.length; i++) {
tempCombination[i] = combination[i] + 1;
}
combinations.add(new HashSet<Integer>(Arrays
.asList(tempCombination)));
}
}
return combinations;
}
private static boolean nextCombination(Integer comb[], int n, int k) {
int i = k - 1;
if (i == -1) {
return false;
//System.out.println("NOT VALID INDEX, n:" + n + ", k:" + k);
}
++comb[i];
/**代码未完, 请加载全部代码(NowJava.com).**/
本文系作者在时代Java发表,未经许可,不得转载。如有侵权,请联系nowjava@qq.com删除。