从指定集合中获取元素组合成不同的字符串.
- 组合生成类(Combination.java)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Combination {
private char[] base;
public Combination(char[] base) {
this.base = base;
}
public List<char[]> getCombinations(int length) {
List<char[]> list = new ArrayList<char[]>();
list.add(new char[length]);
return compose(0, list);
}
private List<char[]> compose(int index, List<char[]> list) {
if (index >= list.get(0).length) {
return list;
}
for (int i = 0, size = list.size(); i < size; i++) {
char[] item = list.get(i);
for (int j = 0; j < base.length; j++) {
if (j > 0) {
item = copy(item);
list.add(item);
}
item[index] = base[j];
}
}
return compose(++index, list);
}
private char[] copy(char[] item) {
return Arrays.copyOf(item, item.length);
}
}
- 调用方式
public class Main {
public static void main(String[] args) {
char[] base = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
Combination combination = new Combination(base);
List<char[]> result = combination.getCombinations(3);
for (char[] cs : result) {
System.out.println( new String(cs));
}
}
}