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. SQL Server之存储过程基础知识

    什么是存储过程呢?存储过程就是作为可执行对象存放在数据库中的一个或多个SQL命令. 通俗来讲:存储过程其实就是能完成一定操作的一组SQL语句. 那为什么要用存储过程呢?1.存储过程只在创造时进行编译, ...

  2. BZOJ-1015 StarWar星球大战 并查集+离线处理

    1015: [JSOI2008]星球大战starwar Time Limit: 3 Sec Memory Limit: 162 MB Submit: 4105 Solved: 1826 [Submit ...

  3. 搭建一个springMVC项目以及遇到的问题

    首先找到jar包(lz现在还在学习maven,以后回了,就用maven了,自己配置时,jar包不全就很容易到时搭建失败)

  4. Bzoj3893 [Usaco2014 Dec]Cow Jog

    Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 302  Solved: 157 Description The cows are out exerci ...

  5. POJ 1469 COURSES

    COURSES Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 20478   Accepted: 8056 Descript ...

  6. windows进程/线程创建过程 --- windows操作系统学习

    有了之前的对进程和线程对象的学习的铺垫后,我们现在可以开始学习windows下的进程创建过程了,我将尝试着从源代码的层次来分析在windows下创建一个进程都要涉及到哪些步骤,都要涉及到哪些数据结构. ...

  7. leach和leach-c协议仿真

    http://blog.csdn.net/codingkid/article/details/7215216 1.复制leach_test为leach-c_test,修改里面的文件夹和输出文件名.并且 ...

  8. 基础总结篇之三:Activity的task相关

    http://blog.csdn.net/liuhe688/article/details/6761337 古人學問無遺力,少壯工夫老始成.紙上得來終覺淺,絕知此事要躬行.南宋.陸遊<冬夜讀書示 ...

  9. 人工神经网络(ANN)

    参考资料:http://www.cnblogs.com/subconscious/p/5058741.html 从函数上来看,神经网络是回归方程的级联叠加,用来逼近目标函数的,本质是一种模拟特征与目标 ...

  10. 织梦DedeCMS删除所有栏目或文章后,新建ID不从1开始的解决方法

    这个修改方法很简单,从模板无忧那里找到的,只需要在后台系统-SQL命令行工具里面运行以下语句即可,不用采用笨方法重新安装织梦CMS了. 删除所有栏目,新建ID从1开始: ALTER TABLE `de ...