"Leetcode" Generate parentheses in JAVA

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:

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

用dfs思想做递归就好了,记好了先写base case,left,right走过一遍了,可以把这个String加进list

Import Java.util.arraylist;import Java.util.list;public class Generateparentheses {public static void main (String args[ ]) {generateparentheses GP = new generateparentheses (); System.out.println (Gp.generateparenthesis (3));} Public list<string> generateparenthesis (int n) {if (n<=0) return null; Arraylist<string>list = new arraylist<string> (); String str = new string ();d FS (list,str,n,n); return list;    } Private Voiddfs (arraylist<string> list, String str, int left, int. right) {if (left>right) Return;//problem with ") ("if (left==0&&right==0) {list.add (str);} if (left>0) DFS (list,str+ "(", Left-1,right), if (right>0) DFS (list, str+ ")", Left,right-1);}}


"Leetcode" Generate parentheses in JAVA

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.