[Question 100] Question 46th matching brackets

Source: Internet
Author: User

I. Question

How many matching arrangement methods can be applied to the four pairs of parentheses? For example, two pairs of parentheses can have two types: () and (())

Ii. Answers

Solution 1: one pair of parentheses is offset.

We can regard the left parenthesis as the 1 right parenthesis.
-1, and then arrange the 8 numbers in full

Determine whether or not each sorting meets the conditions and add them one by one. Sum> = 0 until the traversal of the sequence is complete. If the conditions are met, Count ++

Failed if sum <0 appears

Solution 2: Use eight bits, from 0000
Traversal from 0000 to 1111 1111, with zero Addition
-1: 1 plus
1

If all the bits in the sequence are equal to 0 and sum is always greater than zero during incremental addition, the conditions are met.

3. Source Code


#include<iostream>#include <vector>using namespace std ;void Print(vector<char> v){for (vector<char>::iterator beg=v.begin();beg!=v.end();++beg)cout<<*beg<<" ";cout<<endl;}void MatchNums(int nSize,int nLen,vector<char> &v){int nLeftBrackets=0;int nRightBrackets=0;for (vector<char>::iterator beg=v.begin();beg!=v.end();++beg){if(*beg=='(')nLeftBrackets++;elsenRightBrackets++;if(nRightBrackets>nLeftBrackets)return;if(nLeftBrackets+nRightBrackets==nSize&&nLeftBrackets==nRightBrackets)Print(v);}if (nLen>0){v.push_back('(');MatchNums(nSize,nLen-1,v);v.pop_back();v.push_back(')');MatchNums(nSize,nLen-1,v);v.pop_back();}}int main(){vector <char> v;int n=4;MatchNums(n,n,v);return 1;}

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.