我的代码下面的问题是发现是假的.
它找到密码并进入,return true;但它继续运行.
如何退出递归并停止return true;?
string password = "password";
char[] chars = new char[] { 'a', 'b', 'c', 'c', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's' , 't', 'u', 'v', 'w', 'x', 'y', 'z' };
bool found = MatchPassword(chars, 8, string.Empty, password);
Debug.WriteLine(found);
}
static int counter = 0;
public static bool MatchPassword(char[] chars, int maxLen, string baseGuess, string actualPassword)
{
counter++;
int curLen = baseGuess.Length;
if (curLen == maxLen)
return false;
for (int i = 0; i < chars.Length; i++)
{
string nextGuess = baseGuess + chars[i];
if (counter % 1000000 == 0 || curLen == 0 || nextGuess.StartsWith("passwo")) //
Debug.WriteLine(nextGuess);
if (nextGuess == actualPassword)
return true;
else
MatchPassword(chars, maxLen, nextGuess, actualPassword);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
之前添加一个回报
MatchPassword(chars, maxLen, nextGuess, actualPassword);
Run Code Online (Sandbox Code Playgroud)
该行应该是:
return MatchPassword(chars, maxLen, nextGuess, actualPassword);
Run Code Online (Sandbox Code Playgroud)
这样你基本上"冒泡"了调用堆栈的结果