Given N pairs of parentheses, output all of its legal combined states, for example, n=3, all legal states are: "(()))", "(())", "(())", "(()) ()", "(()) ()", "() (())";
parsing:
Or deep search Dfs idea, the key to the deep search is to record the number of left parenthesis and the number of closing brackets, when the number of left brackets used is less than the right parenthesis is illegal; when the number and greater than 2N are illegal; when the numbers are equal and the number equals 2N is legal.
The code is as follows:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <set > #include <map> #include <cmath> #include <climits> #include <ctime> #include <stack># Include <queue> #include <vector> #include <algorithm> #define MAXN 1010#define RST (n) memset (n, 0, sizeof (N)) using namespace Std;char str[maxn];void solve (int N, int ls, int rs) { if (ls = = rs && ls + rs = = 2*n) { printf ("%s\n", str); return; } if (ls < rs | | ls + rs >= 2*n) return; int index = ls + rs; Str[index] = ' ('; Solve (n, ls+1, RS); Str[index] = ') '; Solve (n, LS, rs+1);} int main () { int n; while (~SCANF ("%d", &n)) { solve (n, 0, 0); } return 0;}
Find all the valid matching brackets (DFS) for the corresponding n---millet pen questions