输出n对括号所有有效的匹配 java实现



原题 为 :Print all combinations of balanced parentheses

input: 3 (e.g., 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))

根据提议分析。我们先取n=3.画出所有的情况。

代码

package parenthesis;

public class Parenthesis {

	static void printParenthesis(int pos , int n , int open ,int close ,char[] buffer){
		//System.out.println("step"+pos+" open is : "+ open + "close is :" + close);
		//System.out.println(new String(buffer));
		if(close == n){
			//System.out.println("over");
			System.out.println(new String(buffer));
			
			return;
		}
		if(open >close){
			buffer[pos]='}';
			printParenthesis(pos+1, n, open, close+1, buffer);
			
		}
		
		if(open 

你可能感兴趣的:(算法)