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

LeetCode Generate Parentheses

时间:2014-10-16 01:27:21      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   sp   div   on   

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     String parenthes = "()";
 3     List<String> lastParenthesis=new ArrayList<>();
 4     public List<String> generateParenthesis(int n) {
 5             List<String> Parenthesis=new ArrayList<>();
 6         if (n==0) {
 7             return lastParenthesis;
 8         }
 9         lastParenthesis.add(parenthes);
10         if (n==1) {    
11             return lastParenthesis;
12         }else {
13             for (int i = 2; i <=n; i++) {
14                 for (String eleP : lastParenthesis) {
15                     for (int j = 0; j < eleP.length(); j++) {
16                         String newone=eleP.substring(0, j+1)+parenthes+eleP.substring(j+1);
17                         if (!Parenthesis.contains(newone)) {
18                             Parenthesis.add(newone);
19                         }
20                     }
21 
22                 }
23                     lastParenthesis.clear();
24                     lastParenthesis.addAll(Parenthesis);
25                     Parenthesis.clear();
26             }
27         }
28         return lastParenthesis;
29     }
30 }

 

LeetCode Generate Parentheses

标签:style   blog   color   io   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/birdhack/p/4027644.html

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