[Leetcode] generate parentheses

Source: Internet
Author: User
Generate parentheses

GivenNPairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenN= 3, a solution set is:

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

Algorithm ideas:

DFS: For each bit, try the suffix '(' or ')', use K to record the number of left parentheses, and use couple to record the matched logarithm. Pay attention to pruning.

This code is the most concise algorithm I have seen: [leetcode] generate parentheses

The Code is as follows:

1 public class solution {2 list <string> result = new arraylist <string> (); 3 public list <string> generateparenthesis (int n) {4 DFS (New stringbuilder (), 0, 0, n); 5 return result; 6} 7 private void DFS (stringbuilder Sb, int K, int couple, int N) {8 If (k = 0 & couple = N & SB. length () = 2 * n) {9 result. add (sb. tostring (); 10 return; 11} 12 if (k <0 | sb. length ()> 2 * n) return; // pruning 13 char [] C = {'(', ')'}; 14 for (INT I = 0; I <2; I ++) {15 k = (I = 0 )? K + 1: K-1; 16 if (k> 0 & I = 1) {// the premise of pairing is k> 0, 17 couple ++; 18 k --; 19} 20 if (k <0) {// if there are left brackets in front of the wood, only 21 k ++; 22 continue; 23} 24 DFS (sb. append (C [I]), K, couple, n); 25 sb. deletecharat (sb. length ()-1); 26} 27} 28}

 

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.