猿问

我的字符串排列算法不起作用

我写了一个算法来解决字符串排列算法。它有问题,某处打印错误的输出。我已经针对不同的输入多次浏览了我的代码,但我无法找到我犯了什么错误。


有人会解释我在哪里犯了错误吗?


public static void main(String args[]) throws Exception {


    String str1 = "eat";

    int len = str1.length();

    char[] str = str1.toCharArray();

    recurPerm(str,0,len);

}

static void recurPerm(char[] str, int strstartind, int sz) {


    for(int i = strstartind; i < sz; i++){

        if(i > strstartind) {


            char temp = str[strstartind];

            str[strstartind] = str[i];

            str[i] = temp;


            recurPerm(str, strstartind + 1, sz);

        }

        else {

            recurPerm(str, strstartind + 1, sz);

        }

    }

    if(strstartind >= sz){

        System.out.println(str);

    }


    return;

}

输出


eat

eta

tea 

tae

eat

eta

但正确的输出是


吃 eta aet 吃 tae 茶


我也试过调试。我发现调试太难了,因为涉及到递归。


慕神8447489
浏览 121回答 1
1回答

哔哔one

您应该恢复递归的原始状态,否则您会不断混淆给定的参数。函数参数 "strstartind" 仅指示要选择的正确字符,如果原始 "str[]" 未更改,但是您会在以下位置覆盖原始 "str[]":&nbsp; &nbsp; str[strstartind] = str[i];&nbsp; &nbsp; str[i] = temp;这是一个有效的解决方案,可以恢复递归参数:public class DemoApplicationTests {public static void main(String args[]) throws Exception {&nbsp; &nbsp; String str1 = "eat";&nbsp; &nbsp; int len = str1.length();&nbsp; &nbsp; char[] str = str1.toCharArray();&nbsp; &nbsp; recurPerm(str, 0, len);}static void recurPerm(char[] str, int strstartind, int sz) {&nbsp; &nbsp; for (int i = strstartind; i < sz; i++) {&nbsp; &nbsp; &nbsp; &nbsp; char temp = str[strstartind];&nbsp; &nbsp; &nbsp; &nbsp; str[strstartind] = str[i];&nbsp; &nbsp; &nbsp; &nbsp; str[i] = temp;&nbsp; &nbsp; &nbsp; &nbsp; recurPerm(str, strstartind + 1, sz);&nbsp; &nbsp; &nbsp; &nbsp; //restore state&nbsp; &nbsp; &nbsp; &nbsp; str[i] = str[strstartind];&nbsp; &nbsp; &nbsp; &nbsp; str[strstartind] = temp;&nbsp; &nbsp; }&nbsp; &nbsp; if (strstartind >= sz) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(str);&nbsp; &nbsp; }&nbsp; &nbsp; return;}}
随时随地看视频慕课网APP

相关分类

Java
我要回答