繁体   English   中英

创建递归方法的返回类型

[英]Creating a return type of a recursive method

我有以下为给定字符串生成排列的递归方法。 我正在尝试为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));
        }
}
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;
    }
}

您可以使用静态列表来“收集”结果:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM