码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Generate Parentheses

时间:2016-03-21 09:22:49      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!