Find all valid parentheses

1593 ワード

Problem:
Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-pairs of parentheses.
正の整数Nが与えられ、以下の例では、可能なすべてのN対括弧シーケンスが印刷される.
EXAMPLE:
input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))
My Code:

public class Parenthese {
	public static void printParentheses(int n){
		printSub(n, 0, 0, "");
	}
	
	public  static void printSub(int n, int l, int r, String s){
		if(l == n && r == n){
			System.out.println("One result:" + s);
			return;
		}else {
			if(l > r){
				if(l < n) {
					String s1 = s + '(';
					printSub(n, l+1, r, s1);
				}
				String s2 = s+ ')';
				printSub(n, l, r+1, s2);
			}
			if(l == r){
				if(l<n){
					String s1 = s + '(';
					printSub(n, l+1, r, s1);
				}
			}
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		printParentheses(4);
	}

}

One result:(((())))
One result:((()()))
One result:((())())
One result:((()))()
One result:(()(()))
One result:(()()())
One result:(()())()
One result:(())(())
One result:(())()()
One result:()((()))
One result:()(()())
One result:()(())()
One result:()()(())

One result:()()()()