有人可以解释与计算机/编程相关的递归这个词吗?我很难理解它的用途



在我的计算课程中,递归这个词被使用了很多 - 我试图更深入地了解它的用法,想知道是否有人可以启发我。

EX:递归搜索 HKLM 以查找密钥 SAM

@vekerdyb的答案是正确的:搜索词中的递归通常意味着在每个(子(级别中进行搜索。当然,递归(在计算机科学中(是一个更普遍(更一般(的概念(另见@Maffe的回答(。

将您的示例作为任务请求"递归搜索 HKLM 以查找密钥 SAM">,那么 Windowscmd中的解决方案可能源于reg.exe实用程序,另请参阅reg query /?帮助中的(截断(摘录:

REG QUERY KeyName [/v [ValueName] | /ve] [/s]
[/f Data [/k] [/d] [/c] [/e]] [/t Type] [/z] [/se Separator]
[/reg:32 | /reg:64]
/s       Queries all subkeys and values recursively (like dir /s).
/f       Specifies the data or pattern to search for.
Use double quotes if a string contains spaces. Default is "*".
/k       Specifies to search in key names only.
/c       Specifies that the search is case sensitive.
The default search is case insensitive.
/e       Specifies to return only exact matches.
By default all the matches are returned.

有关/s开关的说明...递归地(如dir /s(参见dir /? | find /I " /s"

/S    Displays filesin specified directoryand all subdirectories.

现在,您可以看到区别:在 HKLM 中搜索密钥 SAM(不是递归的(

reg query HKLM /K /C /E /F SAM
HKEY_LOCAL_MACHINESAM
End of search: 1 match(es) found.

与递搜索 HKLM 以查找密钥 SAM的比较:

reg query HKLM /K /C /E /F SAM /S
HKEY_LOCAL_MACHINESAM
HKEY_LOCAL_MACHINESAMSAM
HKEY_LOCAL_MACHINESECURITYSAM
HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionAuditSystemPolicyObjectAccessSAM
HKEY_LOCAL_MACHINESYSTEMControlSet001ControlSAM
HKEY_LOCAL_MACHINESYSTEMControlSet001ServicesEventLogSystemSAM
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSAM
HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesEventLogSystemSAM
End of search: 8 match(es) found.

"理解递归的最好方法是理解递归。

一般来说,当你使用某些东西来解释自己时,就会发生递归。

在计算机编程中,当您从自身调用函数/方法时,就会发生递归。例如,此函数:

function printHello() {
print("Hello!")   //this prints "Hello!" on the console
printHello()      //this starts from the beginning
}

将无休止地打印"你好!"无限时间。

递归在不同情况下很有用,例如计算数字的阶乘。

在数学中,n 的阶乘是乘积 (n((n-1((n-2((n-3(...

在编程中,我们可以用递归函数计算数字 n 的阶乘,方式如下:

//recursive
var factorial = function(n) {
if(n == 0) {
return 1
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(num));

@Maffe的答案是正确的,但要扩展到您的示例,搜索词中的"递归"通常意味着在每个级别中进行搜索。

(我不知道在您的示例中HKLMKey SAM是什么,因此我将使用简单的文件系统搜索。

如果您的工作目录/home/user1并且您搜索(非递归(文件test.txt,则意味着您正在搜索名为/home/user1/test.txt的文件。
如果您以递归方式搜索,则意味着您搜索当前目录/home/user1,以及任何子目录(如/home/user1/documents(和子目录的任何子目录(如/home/user1/documents/tests(等。

在伪代码中:

define searchRecursively(path, filename):
results := []
for every file in path:
if file.name is filename:
add file to the list of results
if file.type is directory:
subresults := searchRecursively(file, filename) # this is why it is recursive
add all elements of subresults to results
return results

最新更新