Topic: Programmatic implementation of the legal match for all parentheses. Examples are as follows:
Enter 3
Output ((())) (() ()) (()) () () () () () () ()
Ideas for solving problems:
The scientific name is: Depth First search (DFS) This is to see someone else's article to get the names ...
The code is as follows:
#include "stdafx.h"
#include "iostream"
#include "stdio.h"
#include
#include
using namespace STD;
void func (int left, right of int, vector& str) {
if (left!= 0) {
str.push_back (');
Func (left-1, right, str);
Str.pop_back ();
}
if (right!= 0) {
if (left < right) {
str.push_back (') ');
Func (left, right-1, str);
Str.pop_back ();
}
if (right = = 0) {for
(int i = 0; i < str.size (); i++)
cout<<str[i];
cout << Endl;
}
return;
}
int main () {
int n;
Vector str;
CIN >> N;
Func (n, N, str);
return 1;
}
The program running State is interpreted as follows:
Enter 3
The function call stack is as follows
Step1:
Func (3,3) Push ("(" Call Func (2, 3)
Step2:
Func (2,3) push ("(" Func (1, 3)
Func (3,3)
Step3:
Func (1,3) Push ("(() (() (" Call func (0, 3)
Func (2,3)
Func (3,3)
STEP4:
Func (0,3) Push) "((()" Call func (0, 2)
Func (1,3)
Func (2,3)
Func (3,3)
... No longer repeat here
STEP7:
Func (0,0) print "(())" Return
Func (0,1)
Func (0,2)
Func (0,3)
Func (1,3)
Func (2,3)
Func (3,3)
The next step is to understand this recursive focus
STEP8:
Func (0,1) Pop "(())" Return
Func (0,2)
Func (0,3)
Func (1,3)
Func (2,3)
Func (3,3)
STEP9:
Func (0,2) Pop "(()" Return
Func (0,3)
Func (1,3)
Func (2,3)
Func (3,3)
STEP10:
Func (0,3) Pop "((" return
Func (1,3)
Func (2,3)
Func (3,3)
The process here is the second key 。 Program starts the second traversal
STEP11:
Func (1,3) Pop (("Push") (() "Call Func (1, 2)
Func (2,3)
Func (3,3)
STEP12:
Func (1,2) Push (() (() () ("Call Func" (0, 2)
Func (1,3)
Func (2,3)
Func (3,3)
Omit partial steps here
Step k:
Func (0,0) print "(() ())" Return
Func (0,1)
Func (0,2)
Func (1,2)
Func (1,3)
Func (2,3)
Func (3,3)
Continue to omit some procedures
Step L:
Func (2,3) pop ("Push") "()" Call Func (2, 2)
Func (3,3)
Copyright Notice»[Sohu Written examination] Show all correct brackets match Author: Guanzi This blog all content in the "signature-non-commercial use-to maintain consistent" creation of a common agreement under the publication of the full text reproduced, must contain the copyright information; part of the reprint or reference, please indicate the author's signature and the origin of the article This article link: http://guanzi.info/2013/08/%e6%90%9c%e7%8b%90%e7%ac%94%e8%af%95%e6%98%be%e7%a4%ba%e6%89%80%e6%9c%89%e6%ad %a3%e7%a1%ae%e7%9a%84%e6%8b%ac%e5%8f%b7%e5%8c%b9%e9%85%8d/