Java [leetcode 22]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:

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

解题思路:

利用递归的思想。用left和right分别记录剩余的左,右括号数。

每次都首先把左括号放进字符串中。

放入右括号的条件是:右括号剩余的数目大于0,且左括号剩余数目小于右括号剩余数目。

当left和right都为0时表明字符串已形成,加入到List中。

代码如下:

public class Solution {
    List<String> list = new ArrayList<String>();
	public List<String> generateParenthesis(int n) {
		if (n <= 0)
			return list;
		generate("", n, n);
		return list;
	}
	public void generate(String s, int left, int right) {
		if (left == 0 && right == 0) {
			list.add(s);
			return;
		}
		if (left > 0)
			generate(s + '(', left - 1, right);
		if (right > 0 && right > left)
			generate(s + ')', left, right - 1);
	}
}
原文地址:https://www.cnblogs.com/zihaowang/p/4503831.html