Recursive output all the legitimate sequences of a given n pair of braces

Source: Internet
Author: User

Similar topics are thought to be solved by recursive methods.

Solution: The legal sequence of parentheses, the number of open parentheses already inserted is greater than the number of closing parentheses.

(1) Inserting the opening parenthesis: the remaining brackets, and the left parenthesis;

(2) Insert closing parenthesis: The remaining brackets, the number of closing brackets is greater than the number of left parenthesis;

Code:

public class Parentheses {public
	static void Printpar (int l, int r, char[] str, int count) {
		if (l<0 | | r<l) return;
		if (l==0&&r==0) {
			System.out.println (str);
		} else{
			if (l>0) {
				str[count]= ' (';
				Printpar (L-1, R, str, count+1);
			if (r>l) {
				str[count]= ') ';
				Printpar (l, r-1, str, count+1);
	
	}} public static void Main (string[] args) {
		int count = 4;
		Char str[] = new char[count*2];
		Printpar (count, Count, str, 0);
	}

The results are as follows:

(((())))
((()()))
((())())
((()))()
(()(()))
(()()())
(()())()
(())(())
(())()()
()((()))
()(()())
()(())()
()()(())
()()()()

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.