1. 程式人生 > >LeetCode——Generate Parentheses

LeetCode——Generate Parentheses

href 分享 n) borde parent static cal htm family

Given?n?pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given?n?= 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

原題鏈接:https://oj.leetcode.com/problems/generate-parentheses/

題目:給定n對括號,寫一個函數生成全部的構造良好的括號對。

思路:相似這樣子的東西在組合數學中有學習到,今天再查了一下。就是卡特琳數。

其通項公式為技術分享圖片Cn表示全部包括n組括號的合法運算式的個數。

對於計算,能夠採用遞歸的方式。left、right分別代表"("、")"的數目。

在每次遞歸函數中記錄左括號和右括號的剩余數量,然後有兩種選擇。一個是放一個左括號。還有一種是放一個右括號。當然有一些否定條件。比方剩余的右括號不能比左括號少,或者左括號右括號數量都要大於0。

正常結束條件是左右括號數量都為0。

	public static List<String> generateParenthesis(int n) {
		List<String> list = new ArrayList<String>();
		helper(list,"",0,0,n);
		return list;
	}
	public static void helper(List<String> list,String s,int left,int right,int n){
		if(left < right)
			return;
		if(left == n && right==n){
			list.add(s);
			return;
		}
		if(left == n){
			helper(list,s+")",left,right+1,n);
			return;
		}
		helper(list,s+"(",left+1,right,n);
		helper(list,s+")",left,right+1,n);
	}

reference :?http://blog.csdn.net/linhuanmars/article/details/19873463

? ??http://blog.csdn.net/fightforyourdream/article/details/14159435


LeetCode——Generate Parentheses