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

leetcode--Generate Parentheses

时间:2014-06-11 12:25:51      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   java   com   get   

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Solution {
    /**In order to generate valid parenthesis, the number of
     * "(" should not smaller than the number of ")". So, we use a List<Integer>
     * to save the number of "(". So the number of ")" can be calculated.
     * @param n --Integer, number of parentheses
     * @return List of valid parentheses strings
     * @author Averill Zheng
     * @version 2014-06-04
     * @since JDK 1.7
     */
    public List<String> generateParenthesis(int n) {
        List<String> validParen = new ArrayList<String>();
        List<Integer> numberOfLeftParen = new ArrayList<Integer>();
        if(n > 0){
            validParen.add("(");
            numberOfLeftParen.add(1);
            for(int i = 2; i <= 2*n; ++i){
                List<String> tempValidParen = new ArrayList<String>();
                List<Integer> num = new ArrayList<Integer>();
                int length = validParen.size();
                for(int j = 0; j < length; ++j){
                    //the length of string in list now is i - 1
                    int leftParen = numberOfLeftParen.get(j); // it implies that number of ")" is i - 1 - leftParen                
                    String s = validParen.get(j);
                    if(leftParen == n){
                        tempValidParen.add(s + ")");
                        num.add(leftParen);
                    }
                    else if(leftParen <= (i - 1 - leftParen)){
                        tempValidParen.add(s + "(");
                        num.add(leftParen + 1);
                    }
                    else{
                        tempValidParen.add(s + "(");
                        num.add(leftParen + 1);
                        tempValidParen.add(s + ")");
                        num.add(leftParen);
                    }
                }
                validParen = tempValidParen;
                numberOfLeftParen = num;
            }
        }
        return validParen;
    }
}

  

leetcode--Generate Parentheses,布布扣,bubuko.com

leetcode--Generate Parentheses

标签:class   blog   code   java   com   get   

原文地址:http://www.cnblogs.com/averillzheng/p/3772537.html

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