C++ 递归在循环中是如何工作的?
我知道递归意味着函数调用自己。iteartion意味着有一个循环(while,do…) 我想知道的问题是,当循环中出现递归时,我的程序是如何运行的: **此示例将生成给定strin的所有排列:C++ 递归在循环中是如何工作的?,c++,C++,我知道递归意味着函数调用自己。iteartion意味着有一个循环(while,do…) 我想知道的问题是,当循环中出现递归时,我的程序是如何运行的: **此示例将生成给定strin的所有排列: #include <iostream> #include <windows.h> #include <algorithm> #include <string> using namespace std; void string_permutation( st
#include <iostream>
#include <windows.h>
#include <algorithm>
#include <string>
using namespace std;
void string_permutation( std::string& orig, std::string& perm)
{
if( orig.empty() )
{
std::cout << "perm: " << perm << std::endl;
return;
}
for(int i = 0; i < orig.size(); ++i)
{
std::string orig2 = orig;
orig2.erase(i, 1);
std::string perm2 = perm;
perm2 += orig.at(i);
string_permutation(orig2, perm2);
}
}
int main()
{
system("color 1f");
std::string orig = "123";
std::string perm;
string_permutation(orig, perm);
cout << "Complete!" << endl;
cout << endl << endl << endl;
//system("pause");
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
无效字符串排列(标准::字符串和原始,标准::字符串和排列)
{
if(源空()
{
std::cout递归链深入到size
调用加上一个空字符串。每个递归步骤调用string\u permutation()
size
次提供字符串参数orig
小于一个符号(size-1
)。因此,总共有size!
调用string\u permutation()
生成所有可能的排列
可以用图表来描述:
string_permutation: // top call for entire size N
// start loop for smaller strings size = N - 1
string_permutation:
// start loop for smaller strings size = N - 2
string_permutation: // loop step 0, size = N - 2
// start loop for smaller strings size = N - 3
string_permutation:
//...
string_permutation: // loop step 1, size = N - 2
string_permutation: // loop step 2, size = N - 2
//...
string_permutation:
//...
尾部调用优化不能应用于此类递归。
因此,您应该期望它在堆栈链上创建本地std::string orig2
和std::string perm2
的size
实例,递归和迭代通常不会同时进行。您能解释一下为什么将它们放在一起吗?“想要跟踪我的程序”。您可以使用调试器来执行此操作。