您可以使用一个静态列表 “收” 的结果:
static List<String> perms = new ArrayList<>();
public static void main(String[] args) throws IOException {
permutation("abc");
System.out.println(Arrays.toString(perms.toArray())); // prints [abc, acb, bac, bca, cab, cba]
}
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) {
perms.add(prefix);
}
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1)); // you had a bug in the last index on this line
}
}
或者,您可以创建列表,并将它作为参数传递:
public static void main(String[] args) throws IOException {
List<String> perms = new ArrayList<>();
permutation("abc", perms);
System.out.println(Arrays.toString(perms.toArray())); // print [abc, acb, bac, bca, cab, cba]
}
public static void permutation(String str, List<String> perms) {
permutation("", str, perms);
}
private static void permutation(String prefix, String str, List<String> perms) {
int n = str.length();
if (n == 0) {
perms.add(prefix);
}
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1), perms);
}
}
我真的很难弄清楚“创建返回类型”的含义。 – 2014-09-03 03:26:12
@ChrisMartin他意味着他想从'permutation'返回一些东西,而不是仅仅返回'void'。但是,我仍然不确定究竟应该如何。 – Jashaszun 2014-09-03 03:39:56
你想有一个返回类型在稍后在一个servlet中使用,比如把这些结果字符串放入对象的arraylist中。例如 – user1712095 2014-09-03 03:52:05