我正在尝试解决以下问题:
实施一种算法来打印所有有效的(例如,正确打开和 闭合的n对括号的组合。示例:输入:3 (例如,3对括号)输出:()()(),()(()),(())(),((()))
当我重新调整基本情况并且从堆栈中弹出调用时,它总是跳到下面的部分代码;
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;
}
答案 0 :(得分:2)
您可能正在运行优化代码的调试器。这样做没有错,但优化器可能重新排序了代码。如果无序执行困扰您,请在使用调试器时关闭优化器。