leetcode#22* Generate Parentheses

Source: Internet
Author: User

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

Test instructions: An integer n requirement is combined into a string consisting of n pairs of parentheses, which requires the output of all possible permutations.
Idea: Recursive deep search, notice two conditions, can insert ' (' The condition is must be the remaining number greater than 0, be able to insert ') ' The condition is that the number of the remaining is greater than 0 and the remaining ') ' number is greater than the remaining ' (' number, but be sure to construct a good DFS function parameters.

Class Solution {public
:
    vector<string>ans;           
    vector<string> generateparenthesis (int n) {
        Dfs ("", n,0);
        return ans;
    }
    void Dfs (String s,int l,int r)
    {
        if (l==0&&r==0)
        {
            ans.push_back (s);
            return;
        }
        if (l>0)
        {
            string s1=s+ ' (';
            Dfs (s1,l-1,r+1);
        }
        if (r>0)
        {
            string s1=s+ ') ';
            Dfs (s1,l,r-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.