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:
"((()))", "(()())", "(())()", "()(())", "()()()"
1 public class Solution { 2 ArrayList<String> result = null; 3 public ArrayList<String> generateParenthesis(int n) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 StringBuffer st = new StringBuffer(); 6 result = new ArrayList<String>(); 7 if(n == 0) return result; 8 getRow(st, n , n, 0); 9 return result; 10 } 11 public void getRow(StringBuffer st, int n, int m, int num){ 12 if(n == 0 && m == 0){ 13 result.add(st.toString()); 14 } 15 if(n > 0){ 16 st.append('('); 17 num ++; 18 getRow(st, n - 1, m, num); 19 num --; 20 st.deleteCharAt(st.length() - 1); 21 } 22 if(m > 0 && num > 0){ 23 st.append(')'); 24 num --; 25 getRow(st, n, m - 1, num); 26 num ++; 27 st.deleteCharAt(st.length() - 1); 28 } 29 } 30 }
第三遍:
1 public class Solution { 2 public List<String> generateParenthesis(int n) { 3 List<String> result = new ArrayList<String>(); 4 generate(result, 0, n, n, new StringBuilder()); 5 return result; 6 } 7 8 public void generate(List<String> result,int cur,int left,int right, StringBuilder sb){ 9 if(left == 0 && right == 0) result.add(sb.toString()); 10 if(left > 0){ 11 StringBuilder sbs = new StringBuilder(sb); 12 sbs.append('('); 13 generate(result, cur + 1, left - 1, right, sbs); 14 } 15 if(right > 0 && cur > 0){ 16 StringBuilder sbs = new StringBuilder(sb); 17 sbs.append(')'); 18 generate(result, cur - 1, left, right - 1, sbs); 19 } 20 } 21 }
posted on 2013-10-16 07:47 Step-BY-Step 阅读(143) 评论(0) 编辑 收藏 举报