生成括号

题设要求:如果有n对括号,它们一共有多少种组合呢?
譬如对于 n = 3 n=3 n=3,有以下5种情况:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

问题分析:一对括号表示左括号“(” 和右括号 “)”是成对出现的。

代码

    /*
	 * 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 ArrayList<String> generateParenthesis(int n) {
      ArrayList<String> res = new ArrayList<>();
      generateParenthesisCore(n,n,"",res);
      return res;
	}

	private void generateParenthesisCore(int left, int right, String temp, ArrayList<String> res)
	{
		if(left<0||right<0||left>right) return;
		if(left==0 && right==0) {
			res.add(temp);
			return;
		}
		generateParenthesisCore(left-1, right, temp+"(", res);
		generateParenthesisCore(left, right-1, temp+")", res);
	}

你可能感兴趣的:(Java编程)