Find all the valid matching brackets (DFS) for the corresponding n---millet pen questions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.