1. 程式人生 > >輸出n對括號所有有效的匹配 java實現

輸出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 <n){
			buffer[pos] = '{';
			printParenthesis(pos+1, n, open+1, close, buffer);
		}
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//System.out.println("012142");
		int  n = 4;
		char[] cs = new char[8];
		printParenthesis(0, 4, 0, 0, cs);
		//System.out.println("012143");
	}

}