如何停止递归?

How to stop recursion?

我正在开展一个学校项目 (java 类)。目的是研究和创建一些暴力密码破解算法(当我不知道密码的长度时,所以我尝试所有最多 x 个字符的密码)并比较它们的工作速度。多亏了你的建议,我才能够创建这个看起来比以前的算法更有条理的算法。但是,我遇到了 recursion

的一个问题
 if (keepworking) {
            for (int i = 1; i <= 5; i++) {
                possibleCombinations(i, CHOICES, "");
            }
        }
.....
public static void possibleCombinations(int maxLength, char[] list, String curr) {
    if (curr.length() == maxLength) {
        tries++;
        if (curr.equals(password)) {
            System.out.println(curr);
            keepworking = false;
            return;
        }
    } else {
        for (int i = 0; i < list.length; i++) {
            String oldCurr = curr;
            curr = curr + CHOICES[i];
            possibleCombinations(maxLength, CHOICES, curr);
            curr = oldCurr;
        }
    }
}

运行良好,它找到了密码,但程序继续。它总是尝试所有可能的组合(尝试次数总是 1178420165) 即使密码只有 1 个字符。我正在尝试 在找到密码 后停止递归,但我没有成功。我需要程序尽可能快

你能告诉我为什么它不会停止以及如何正确地停止吗?

就跳出循环而言,我只想设置一个条件来检查 keepworking 标志,例如:

public static void possibleCombinations(int maxLength, char[] list, String curr) {
    if(!keepworking){
      return;
    }
    if (curr.length() == maxLength) {
        tries++;
        if (curr.equals(password)) {
            System.out.println(curr);
            keepworking = false;
            return;
        }
    } else {
        for (int i = 0; i < list.length; i++) {
            String oldCurr = curr;
            curr = curr + CHOICES[i];
            possibleCombinations(maxLength, CHOICES, curr);
            curr = oldCurr;
        }
    }
}

现在,关于正确地做这件事,我们应该 return 一个标志或其他东西,而不是取决于全局变量。查看 this SO 答案以获得详细解释。

我不确定你为什么要尝试使用 while 循环,因为递归有它自己的循环。我写了一些伪代码来帮助您了解您可能要尝试做什么。这看起来像是一项家庭作业,所以我会把硬编码留给你。

maxLength, password, curr

possibleCombinations(int maxLength, password, String curr) 
{
    if (curr.length == maxLength && curr != password)// The only other thing I would do with this condition is to make it also check if you used all the possible chars available. I'll leave that to you.
    {
        //Print message for password not found
    }
    else if (curr == password)
    {
        //print the found password
    }
    else
    {
        // brute force by changing the last char by one and 
        // if it is at the end of the char value limit, 
        // increase the first char by one and apply this same rule until
        // all of the char's values are maxed and add a new char to the end of the string.
        then,
        possibleCombinations(maxLength,password,curr)
    }
}

递归的要点是运行通过相同的例程,直到找到结束例程的条件。您不一定需要使用布尔值来破解密码,因为退出条件将在您匹配时出现。