为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕神8447489 2021-06-07 17:43:49
我写了一个算法来解决字符串排列算法。它有问题,某处打印错误的输出。我已经针对不同的输入多次浏览了我的代码,但我无法找到我犯了什么错误。有人会解释我在哪里犯了错误吗?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;}输出eatetatea taeeateta但正确的输出是吃 eta aet 吃 tae 茶我也试过调试。我发现调试太难了,因为涉及到递归。
查看完整描述

1 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

您应该恢复递归的原始状态,否则您会不断混淆给定的参数。函数参数 "strstartind" 仅指示要选择的正确字符,如果原始 "str[]" 未更改,但是您会在以下位置覆盖原始 "str[]":


    str[strstartind] = str[i];

    str[i] = temp;

这是一个有效的解决方案,可以恢复递归参数:


public class DemoApplicationTests {


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++) {

        char temp = str[strstartind];

        str[strstartind] = str[i];

        str[i] = temp;

        recurPerm(str, strstartind + 1, sz);

        //restore state

        str[i] = str[strstartind];

        str[strstartind] = temp;

    }

    if (strstartind >= sz) {

        System.out.println(str);

    }


    return;

}

}


查看完整回答
反对 回复 2021-06-10
  • 1 回答
  • 0 关注
  • 120 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信