LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj

Question:

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

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

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

Ideas:

For n "(" and n ")", ensure that the number of "(" is greater than ")" In recursion.

package recursion;import java.util.ArrayList;import java.util.List;public class GenerateParentheses {    public List<String> generateParenthesis(int n) {        List<String> res = new ArrayList<String>();        generate(res, n, n, "");        return res;    }        private void generate(List<String> res, int left, int right, String s) {        if (left == 0 && right == 0) {            res.add(s);            return;        }                if (left > 0)             generate(res, left - 1, right, s + "(");                if (right > 0 && right > left)             generate(res, left, right - 1, s + ")");            }        public static void main(String[] args) {        // TODO Auto-generated method stub        GenerateParentheses g = new GenerateParentheses();        for (String s : g.generateParenthesis(3)) {            System.out.println(s);        }    }}

 

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.