String database[] = {'a', 'b', 'c'};
我想根据给定的database
.
a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
...
我只能想到一个非常“虚拟”的解决方案。
public class JavaApplication21 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
char[] database = {'a', 'b', 'c'};
String query = "a";
StringBuilder query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
query = query_sb.toString();
System.out.println(query);
}
query = "aa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
query = query_sb.toString();
System.out.println(query);
}
}
query = "aaa";
query_sb = new StringBuilder(query);
for (int a = 0; a < database.length; a++) {
query_sb.setCharAt(0, database[a]);
for (int b = 0; b < database.length; b++) {
query_sb.setCharAt(1, database[b]);
for (int c = 0; c < database.length; c++) {
query_sb.setCharAt(2, database[c]);
query = query_sb.toString();
System.out.println(query);
}
}
}
}
}
解决方案非常愚蠢。从某种意义上说,它是不可扩展的
- 如果我增加 的大小
database
怎么办? - 如果我的最终目标打印字符串长度需要为 N 怎么办?
是否有任何智能代码可以以非常智能的方式生成可扩展的排列和组合字符串?