标签:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Given n = 3
, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
public class Solution { /** * @param n n pairs * @return All combinations of well-formed parentheses */ public ArrayList<String> generateParenthesis(int n) { // Write your code here ArrayList<String> result = new ArrayList<String>(); if(n <= 0) return result; StringBuilder line = new StringBuilder(); helper(result, line, 0, 0, n); return result; } public void helper(ArrayList<String> result, StringBuilder line, int left_num, int right_num, int n){ if(left_num < right_num || left_num > n || right_num > n){ return; } if(left_num == right_num && left_num == n){ result.add(line.toString()); return; } line.append(‘(‘); helper(result, line, left_num + 1, right_num, n); line.deleteCharAt(line.length() - 1); line.append(‘)‘); helper(result, line, left_num, right_num + 1, n); line.deleteCharAt(line.length() - 1); return; } }
lintcode-medium-Generate Parentheses
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5300505.html