leetcode--Generate Parentheses

来源:互联网 发布:linux 匹配文件名 编辑:程序博客网 时间:2024/06/09 21:28

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:

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

[java] view plain copy
  1. public class Solution {  
  2.     public List<String> generateParenthesis(int n) {  
  3.         List<String> result = new ArrayList<String>();  
  4.         solve(00, n, result, "");  
  5.         System.out.println(result);  
  6.         return result;  
  7.     }  
  8.   
  9.     void solve(int left,int right,int n,List<String> result,String str){  
  10.         if(left<right) return;//left括号数目一定要比右边多  
  11.         if(left==n && right==n){//如果左右括号数目相等则添加到list  
  12.             result.add(str);  
  13.             return;  
  14.         }  
  15.         if(left==n){//左括号已满,只能添加右括号  
  16.             solve(left, right+1, n, result, str+")");  
  17.             return;  
  18.         }  
  19.         solve(left+1, right, n, result, str+"(");//继续添加左括号  
  20.         solve(left, right+1, n, result, str+")");//继续添加右括号  
  21.     }  
  22. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/45577891