[Leetcode] generate parentheses

Source: Internet
Author: User

Question: given a number N, find the possible string that makes up n pairs of parentheses

Algorithm: matching parentheses using stacks

1. "(", directly press "(" into Stack, string 2. ")", if the top of the stack is "(", the top element of the stack is displayed and ")" is added to the string.
public class Solution {    private List<String> parenthesesList = new ArrayList<String>();     public List<String> generateParenthesis(int n) {        Stack<String> stack = new Stack<String>();        dfs(stack, "", n);        return parenthesesList;    }        /**     * Algorithm:     *      * 1. Add "(", stack push "(" directly     * 2. Add ")", if the top of stack is "(", pop it     *      */    public void dfs(Stack<String> stack, String parentheses, int nParentheses) {    if (parentheses.length() >= nParentheses*2) {    if (parentheses.length()==nParentheses*2 && stack.empty()) {    parenthesesList.add(parentheses);    }    return ;    }        // push "("    stack.push("(");    dfs(stack, parentheses+"(", nParentheses);    stack.pop();    // push ")"    if (!stack.empty() && stack.peek()=="(") {    stack.pop();    dfs(stack, parentheses+")", nParentheses);    stack.push("(");    }    }}

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.