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 List<String> generateParenthesis(int n) {
- List<String> result = new ArrayList<String>();
- solve(0, 0, n, result, "");
- System.out.println(result);
- return result;
- }
-
- void solve(int left,int right,int n,List<String> result,String str){
- if(left<right) return;
- if(left==n && right==n){
- result.add(str);
- return;
- }
- if(left==n){
- solve(left, right+1, n, result, str+")");
- return;
- }
- solve(left+1, right, n, result, str+"(");
- solve(left, right+1, n, result, str+")");
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/45577891