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:

"((()))", "(()())", "(())()", "()(())", "()()()"

解题思路一:

通过观察n=2和n=3的情况可以知道,只要在n=2的String 开头、末尾、'(' 插入“()”即可,注意防止重复。

JAVA实现如下:

static public List<String> generateParenthesis(int n) {
HashSet<String> set = new HashSet<String>();
if (n == 1)
set.add("()");
if (n > 1) {
ArrayList<String> lastList = new ArrayList<String>(
generateParenthesis(n - 1));
StringBuilder sb = new StringBuilder();
for (String string : lastList) {
sb = new StringBuilder(string);
set.add(sb.toString() + "()");
set.add("()" + sb.toString());
for (int i = 0; i < sb.length() - 1; i++) {
if (sb.charAt(i) == '(') {
sb.insert(i + 1, "()");
set.add(sb.toString());
}
sb = new StringBuilder(string);
}
}
}
return new ArrayList<String>(set);
}

解题思路二:

通过观察可以发现,任何符合条件的Parenthesis(n)总是可以分解为(generateParenthesis(k))+generateParenthesis(n-1-k),同时由于后半部分generateParenthesis(n-1-k)的唯一性,这种算法不会产生重复的元素,因此采用DFS进行一次遍历即可,这种算法更高效!JAVA实现如下:

static public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>(), leftList, rightList;
if (n == 0)
list.add("");// 很关键,不能删除
if (n == 1)
list.add("()");
else {
for (int i = 0; i < n; i++) {
leftList = generateParenthesis(i);
rightList = generateParenthesis(n - i - 1);
for (String leftPart:leftList)
for (String rightPart:rightList)
list.add("(" + leftPart + ")" + rightPart);
}
}
return list;
}

C++:

  class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string>res;
if (n == ) {
res.push_back("");
return res;
}
if (n == ) {
res.push_back("()");
return res;
}
for (int i = ; i < n; i++) {
vector<string> left = generateParenthesis(i);
vector<string>right = generateParenthesis(n-i-);
for (string leftPart : left)
for (string rightPart : right)
res.push_back("(" + leftPart + ")" + rightPart);
}
return res;
}
};

【JAVA、C++】LeetCode 022 Generate Parentheses的更多相关文章

  1. 【JAVA、C++】LeetCode 020 Valid Parentheses

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  2. 【JAVA、C++】LeetCode 005 Longest Palindromic Substring

    Given a string S, find the longest palindromic substring in S. You may assume that the maximum lengt ...

  3. 【JAVA、C++】LeetCode 002 Add Two Numbers

    You are given two linked lists representing two non-negative numbers. The digits are stored in rever ...

  4. 【JAVA、C++】LeetCode 010 Regular Expression Matching

    Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...

  5. 【JAVA、C++】 LeetCode 008 String to Integer (atoi)

    Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...

  6. 【JAVA、C++】LeetCode 007 Reverse Integer

    Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 解题思路:将数字 ...

  7. 【JAVA、C++】LeetCode 006 ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  8. 【JAVA、C++】LeetCode 004 Median of Two Sorted Arrays

    There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two ...

  9. 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters. For example, ...

随机推荐

  1. 【Gym 100610A】Alien Communication Masterclass

    题 Andrea is a famous science fiction writer, who runs masterclasses for her beloved readers. The mos ...

  2. BZOJ-1061 志愿者招募 线性规划转最小费用最大流+数学模型 建模

    本来一眼建模,以为傻逼题,然后发现自己傻逼...根本没想到神奇的数学模型..... 1061: [Noi2008]志愿者招募 Time Limit: 20 Sec Memory Limit: 162 ...

  3. SpringMVC配置数据库连接池

    http://www.cnblogs.com/coqn/archive/2012/08/15/SpringMvc%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA%E9%85%8 ...

  4. ASP.NET MVC 中将数据从View传递到控制器中的三种方法(表单数据绑定)

    http://www.cnblogs.com/zyqgold/archive/2010/11/22/1884779.html 在ASP.NET MVC框架中,将视图中的数据传递到控制器中,主要通过发送 ...

  5. sencha touch pull-refresh-panel 面板下拉刷新

    转自:http://www.cnblogs.com/mlzs/archive/2013/06/04/3117518.html 此效果手机未测试,目测没问题,我是搬运工... 演示地址:http://s ...

  6. js正则表达式中的问号几种用法小结

    这篇文章主要介绍了js正则表达式中的问号几种用法,比如+?,*?,{2,3}?可以停止匹配的贪婪模式,感兴趣的朋友可以参考下 在表示重复的字符后面加问号,比如+?,*?,{2,3}?可以停止匹配的贪婪 ...

  7. 锋利的jQuery-7--query ui效果库--拖动排序插件sortable

    一个简单的拖动排序效果,具体请参看jQuery ui官网demo. jquery ui :http://jqueryui.com/ sortable例子:http://jqueryui.com/sor ...

  8. WPF 窗体拖转时不触发MouseLeftButtonUpEvent

    解决方案:手动添加Handler,因为e.Handled这个属性是用在路由事件中的,当某个控件得到一个RoutedEvent,就会检测Handled是否为true,为true则忽略该事件. //手动注 ...

  9. 各种工具使用手册:http://www.itshouce.com.cn/linux/linux-tcpdump.html 关于tcpdump!!!!

    各种工具使用手册:http://www.itshouce.com.cn/linux/linux-tcpdump.html 关于tcpdump!!!! 实用tcpdump命令 //查看本机与mysql的 ...

  10. IMAP(Internet Mail Access Protocol,Internet邮件访问协议)以前称作交互邮件访问协议(Interactive Mail Access Protocol)。

    IMAP(Internet Mail Access Protocol,Internet邮件访问协议)以前称作交互邮件访问协议(Interactive Mail Access Protocol).IMA ...