Question:
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 class Solution { public ArrayList<String> generateParenthesis(int n) { ArrayList<String> results = new ArrayList<String>(); if (n == 0) { results.add(""); return results; } if (n == 1) { results.clear(); results.add("()"); return results; } results.clear(); if (n > 1) { subGenerate(n, "", 0, 0, results); } return results; } private void subGenerate(int n, String result, int left, int right, ArrayList<String> results) { if (left==n) { while(n-right>0){ result+=")"; right++; } results.add(result); return; } subGenerate(n, result+"(", left+1, right, results); if (left>right) { subGenerate(n, result+")", left, right+1, results); } } }
leetcode Generate Parentheses 难度系数3 3.10
原文:http://blog.csdn.net/yiding_he/article/details/18893387