问题描述
我正在尝试解决以下问题:
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses. EXAMPLE: input: 3 (e.g., 3 pairs of parentheses) output: ()()(), ()(()), (())(), ((()))
当我研究基本情况时,当调用从堆栈中弹出时,它总是跳转到代码的后续部分;
cout <<"==============> RESTART HERE " << endl;
问题
为什么在return 语句 之后光标没有返回到函数的开头。为什么从cout <<"==============> RESTART HERE " << endl;
重新启动
例如,在这段代码中,它总是从头开始:
void HelloWorld(int count)
{
if(count<1) return;
if(count<0) return;
cout << " Hello World!" << endl;
HelloWorld(count - 1);
}
下图是第一次运行的调用栈。
源代码
# include<stdio.h>
#include <iostream>
using namespace std;
# define MAX_SIZE 100
void _printParenthesis(int pos, int n, int open, int close);
/* Wrapper over _printParenthesis()*/
void printParenthesis(int n)
{
if(n > 0)
_printParenthesis(0, n, 0, 0);
return;
}
void _printParenthesis(int pos, int n, int open, int close)
{
static char str[MAX_SIZE];
if(close == n)
{
cout <<" open " << open <<" close " << close <<" " << pos<< endl;
cout << str << endl;
return;
}
else
{
if(close < open) {
str[pos] = '}';
cout <<" B open " << open <<" close " << close <<" " << pos<< " }" << endl;
_printParenthesis(pos+1, n, open, close+1);
}
cout <<"==============> RESTART HERE " << endl;
if(open < n) {
str[pos] = '{';
cout <<" A open " << open <<" close " << close <<" " <<pos << " {" << endl;
_printParenthesis(pos+1, n, open+1, close);
}
}
}
/* driver program to test above functions */
int main()
{
int n = 3;
printParenthesis(n);
getchar();
return 0;
}
最佳答案
您可能正在优化代码上运行调试器。这样做没有错,但优化器可能重新排序了代码。如果乱序执行困扰您,请在使用调试器时关闭优化器。
关于c++ - 堆栈调用 : why is the cursor jumping to a specific position of the recursive function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41666417/