[Leetcode 22]generate parentheses

Source: Internet
Author: User

1 Topics:

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

2 Ideas:

This problem thought for a long time, can't think out solution. Find others to solve with recursion. Https://leetcode.com/discuss/14436/concise-recursive-c-solution

Recursion is a thought ah, a function of thinking?

It is not easy to feel completely learned and used.

M represents the left parenthesis, and N represents the right parenthesis.

3 Code:

     PublicList<string> Generateparenthesis (intN) {List<String> result =NewArraylist<string>(); Helper (result,"", N, 0); returnresult; }        Private voidHelper (list<string> list,string String,intMintN) {        if(M==0 && n==0) {List.add (string); return; }                if(M > 0) Helper (list,string+ "(", m-1,n+1); if(n > 0) Helper (list,string+ ")", m,n-1); }

Time complexity, I draw recursive tree, found that the maximum time complexity is O (2^n), there are different views can be a message to discuss together.

[Leetcode 22]generate parentheses

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.