【问题标题】:Recursively computing all possible permutations of a string Java [closed]递归计算字符串Java的所有可能排列[关闭]
【发布时间】:2018-02-25 21:13:43
【问题描述】:

我正在尝试使用 Java 中的递归来计算给定字符串的所有可能排列。但是,我不知道我的代码有什么问题。

这是我的算法:

public static ArrayList<String> computeAllPossiblePermutations(String str) {
    ArrayList<String> perms = new ArrayList<>();
    //base case
    if (str.length() == 1)
        perms.add(str);
    else {
        //loop over the string
        for (int i = 0; i < str.length() - 1; i++) {
            //make a subset of the string excluding the first char
            String sub = str.substring(i + 1, str.length());
            //compute permutations of the subset
            ArrayList<String> subPerms = computeAllPossiblePermutations(sub);
            //add the first char that we excluded at the start of each permutations
            for (String s : subPerms) {
                s = str.charAt(i) + s;
                perms.add(s);
            }
        }
    }
    return perms;
}

【问题讨论】:

    标签: java string recursion permutation


    【解决方案1】:

    有几个问题:

    1. 以下行:String sub = str.substring(i+1, str.length()); 忽略第一个字符
    2. 同一行还将索引i 之后的任何内容视为保持不变的子字符串的“块”,而为了生成排列,我们应该在其余字符的任意两个字符之间插入当前(第一个)字符字符串 - 并为每个排列执行此操作
    3. s = str.charAt(i) + s; 行在 #2 中重复了同样的错误

    这是一个建议的修复方法:


    public static ArrayList<String> computeAllPossiblePermutations(String str) {
        ArrayList<String> perms = new ArrayList<>();
        if (str.length() == 1) {
            perms.add(str);
        } else {
            String chr = str.substring(0,1);
            String rest = str.substring(1);
            ArrayList<String> subPerms = computeAllPossiblePermutations(rest);
            for (String s : subPerms) {
                for (int j = 0; j <= s.length(); j++) {
                    String newPerm = s.substring(0,j) + chr + s.substring(j);
                    perms.add(newPerm);
                }
            }
        }
        return perms;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 2016-04-06
      • 2011-11-22
      • 2020-03-15
      • 1970-01-01
      • 2017-02-17
      • 2012-08-24
      • 2013-05-18
      相关资源
      最近更新 更多