Generate Parentheses

原题:

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:

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

这是一个排列组合的问题, 所有组合的个数其实是一个卡特兰数。

本题有简单解法

依据:

其实对于某个合法的字符串,我们可以发现从合法字符串的任何一个位置看,“(”的数目 >= ")"的数目,即剩余的“(”的数目 <= 剩余的")"数目

代码:

public List<String> generateParenthesis(int n) {
		List<String> result = new ArrayList<String>();
		doGenerateParenthesis(result, "(", 1, 0, n);
		return result;
    }
	
	private void doGenerateParenthesis (List<String> result, String str, 
			int leftParNum, int rightParNum, int n) {
		if(leftParNum==n && rightParNum==n) {
			result.add(str);
			return ;
		}
		if(leftParNum < rightParNum) {
			return ;
		}
		if(leftParNum < n) {
			doGenerateParenthesis(result, str+"(", leftParNum+1, rightParNum, n);
		}
		if(rightParNum < n) {
			doGenerateParenthesis(result, str+")", leftParNum, rightParNum+1, n);
		}
	}

另一种比较好的写法

public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> rst = new ArrayList<String>();
        if(n <= 0) {
            return rst;
        }
        getPair(rst, "", n, n);
        return rst;
    }
    
	public void getPair( ArrayList<String> rst , String s, int left, int right) {
		if(left > right || left < 0 || right < 0) {
			return; 	
		}
		if(left == 0 && right == 0) {
			rst.add(s);
			return;
		}

		getPair(rst, s + "(", left - 1, right);
		getPair(rst, s + ")", left, right - 1);
	}
}






你可能感兴趣的:(Generate Parentheses)