我有以下递归方法,为给定字符串生成排列。我正在尝试为arraylist中生成的字符串创建一个返回类型,更具体地说,我正在尝试在jsp页面中打印输出。
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+ n));
}
}
答案 0 :(得分:1)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Permute {
public static void main(String[] args) {
System.out.println(findAllPermutations("abc"));
}
public static List<String> findAllPermutations(String s) {
if (s == null) {
throw new NullPointerException();
}
if (s.length() <= 1) {
return Arrays.asList(s);
}
List<String> permutations = new ArrayList<>();
for (String permutation : findAllPermutations(s.substring(1))) {
char ch = s.charAt(0);
for (int i = 0; i <= permutation.length(); i++) {
String prefix = permutation.substring(0, i);
String suffix = permutation.substring(i);
permutations.add(prefix + ch + suffix);
}
}
return permutations;
}
}
答案 1 :(得分:0)
您可以使用静态列表“收集”结果:
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);
}
}