Link:http://oj.leetcode.com/problems/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 public ArrayList<String> result = new ArrayList<String>(); 3 4 public ArrayList<String> generateParenthesis(int n) { 5 if (n < 1) 6 return result; 7 result = new ArrayList<String>(); 8 String temp = ""; 9 //recursion(left,right,temp); 10 recursion(n, n, temp); 11 return result; 12 } 13 14 public void recursion(int left, int right, String temp) { 15 if (left == 0 && right == 0) { 16 result.add(temp); 17 return; 18 } 19 if (left == 0) { 20 recursion(left, right - 1, temp + ")"); 21 return; 22 } 23 if (right == 0) 24 return; 25 26 if (left > right) 27 return; 28 recursion(left - 1 , right, temp + "("); 29 recursion(left, right - 1, temp + ")"); 30 } 31 }