`
standalone
  • 浏览: 609857 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Find all valid parentheses

阅读更多
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:()()()()
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics