使用辅助方法的Java置换递归

问题描述 投票:0回答:1

我在使用permutationHelper方法的作业中遇到错误。

称为zybooks的自动评分系统没有告诉我我出了什么问题。。

但是,这给了我一个错误:

Test feedback : permutation("123") incorrectly returned我的输出显示:Your output : 123 132 213 231 312 321imo看起来完全像它应该的那样。

(教师在示例代码中留下示例)

我非常想了解为什么我会收到此错误,即使代码似乎运行正常。 如果有更好的方法可以完成任务。

不允许更改参数或方法的标题。

以下是我的代码。

    /*
    * The following method is given to you, and you will be responsible for completing the permutationHelper method it calls.
    * Sometimes, helper methods are used for recursive methods when another parameter is needed to recursively call a method repeatedly, but passing that parameter initially doesn't make sense.
    */
    public static String permutation(String word){
        return permutationHelper(" ", word);
    }

    /* permutationHelper()
    * This method is called by the permutation method.
    * Given a string, return a string that lists all possible permutations of the letters in the string, with spaces preceding each permutation.
    * For example, "123" would give "123 132 213 231 312 321". 
    * The perm parameter keeps track of the current permutation you are creating.
    * Consider using the a for loop to call the method recursively a certain number of times with different parameters, so you cover all permutations.
    */
    public static String permutationHelper(String perm, String word) {
        if (word.isEmpty()) return perm;
        String a = "";

        for (int i = 0; i < word.length(); i++)
        {
            a += permutationHelper(perm.trim() + word.charAt(i) + " ", word.substring(0, i) + word.substring(i+1, word.length()));
        }
        return a;
    }  

任何指导将不胜感激。

java recursion permutation
1个回答
0
投票
    /*
* The following method is given to you, and you will be responsible for completing the permutationHelper method it calls.
* Sometimes, helper methods are used for recursive methods when another parameter is needed to recursively call a method repeatedly, but passing that parameter initially doesn't make sense.
*/
public static String permutation(String word){
    return permutationHelper(" ", word);
}

/* permutationHelper()
* This method is called by the permutation method.
* Given a string, return a string that lists all possible permutations of the letters in the string, with spaces preceding each permutation.
* For example, "123" would give "123 132 213 231 312 321". 
* The perm parameter keeps track of the current permutation you are creating.
* Consider using the a for loop to call the method recursively a certain number of times with different parameters, so you cover all permutations.
*/
public static String permutationHelper(String perm, String word) {
    if (word.isEmpty()) return perm;
    String a = "";

    for (int i = 0; i < word.length(); i++) a += permutationHelper(perm + word.charAt(i), word.substring(0, i) + word.substring(i+1, word.length()));
    return a;
}   
© www.soinside.com 2019 - 2024. All rights reserved.