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:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
  

在 LeetCode 中有关括号的题共有七道,除了这一道的另外六道是 Score of ParenthesesValid Parenthesis String, Remove Invalid ParenthesesDifferent Ways to Add ParenthesesValid Parentheses 和 Longest Valid Parentheses。这道题给定一个数字n,让生成共有n个括号的所有正确的形式,对于这种列出所有结果的题首先还是考虑用递归 Recursion 来解,由于字符串只有左括号和右括号两种字符,而且最终结果必定是左括号3个,右括号3个,所以这里定义两个变量 left 和 right 分别表示剩余左右括号的个数,如果在某次递归时,左括号的个数大于右括号的个数,说明此时生成的字符串中右括号的个数大于左括号的个数,即会出现 ')(' 这样的非法串,所以这种情况直接返回,不继续处理。如果 left 和 right 都为0,则说明此时生成的字符串已有3个左括号和3个右括号,且字符串合法,则存入结果中后返回。如果以上两种情况都不满足,若此时 left 大于0,则调用递归函数,注意参数的更新,若 right 大于0,则调用递归函数,同样要更新参数,参见代码如下:

C++ 解法一:

class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
generateParenthesisDFS(n, n, "", res);
return res;
}
void generateParenthesisDFS(int left, int right, string out, vector<string> &res) {
if (left > right) return;
if (left == && right == ) res.push_back(out);
else {
if (left > ) generateParenthesisDFS(left - , right, out + '(', res);
if (right > ) generateParenthesisDFS(left, right - , out + ')', res);
}
}
};

Java 解法一:

public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<String>();
helper(n, n, "", res);
return res;
}
void helper(int left, int right, String out, List<String> res) {
if (left < 0 || right < 0 || left > right) return;
if (left == 0 && right == 0) {
res.add(out);
return;
}
helper(left - 1, right, out + "(", res);
helper(left, right - 1, out + ")", res);
}
}

再来看那一种方法,这种方法是 CareerCup 书上给的方法,感觉也是满巧妙的一种方法,这种方法的思想是找左括号,每找到一个左括号,就在其后面加一个完整的括号,最后再在开头加一个 (),就形成了所有的情况,需要注意的是,有时候会出现重复的情况,所以用set数据结构,好处是如果遇到重复项,不会加入到结果中,最后我们再把set转为vector即可,参见代码如下::

n=1:    ()

n=2:    (())    ()()

n=3:    (()())    ((()))    ()(())    (())()    ()()()

C++ 解法二:

class Solution {
public:
vector<string> generateParenthesis(int n) {
unordered_set<string> st;
if (n == ) st.insert("");
else {
vector<string> pre = generateParenthesis(n - );
for (auto a : pre) {
for (int i = ; i < a.size(); ++i) {
if (a[i] == '(') {
a.insert(a.begin() + i + , '(');
a.insert(a.begin() + i + , ')');
st.insert(a);
a.erase(a.begin() + i + , a.begin() + i + );
}
}
st.insert("()" + a);
}
}
return vector<string>(st.begin(), st.end());
}
};

Java 解法二:

public class Solution {
public List<String> generateParenthesis(int n) {
Set<String> res = new HashSet<String>();
if (n == 0) {
res.add("");
} else {
List<String> pre = generateParenthesis(n - 1);
for (String str : pre) {
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == '(') {
str = str.substring(0, i + 1) + "()" + str.substring(i + 1, str.length());
res.add(str);
str = str.substring(0, i + 1) + str.substring(i + 3, str.length());
}
}
res.add("()" + str);
}
}
return new ArrayList(res);
}
}

Github 同步地址:

https://github.com/grandyang/leetcode/issues/22

类似题目:

Remove Invalid Parentheses

Different Ways to Add Parentheses

Longest Valid Parentheses

Valid Parentheses

Score of Parentheses

Valid Parenthesis String

参考资料:

https://leetcode.com/problems/generate-parentheses/

https://leetcode.com/problems/generate-parentheses/discuss/10127/An-iterative-method.

https://leetcode.com/problems/generate-parentheses/discuss/10337/My-accepted-JAVA-solution

https://leetcode.com/problems/generate-parentheses/discuss/10105/Concise-recursive-C%2B%2B-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Generate Parentheses 生成括号的更多相关文章

  1. [CareerCup] 9.6 Generate Parentheses 生成括号

    9.6 Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-p ...

  2. generate parentheses(生成括号)

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  3. [LintCode] Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  4. [LeetCode] 22. Generate Parentheses 生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  5. [leetcode]22. Generate Parentheses生成括号

    Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...

  6. 022 Generate Parentheses 生成括号

    给 n 对括号,写一个函数生成所有合适的括号组合.比如,给定 n = 3,一个结果为:[  "((()))",  "(()())",  "(())() ...

  7. LeetCode Generate Parentheses 构造括号串(DFS简单题)

    题意: 产生n对合法括号的所有组合,用vector<string>返回. 思路: 递归和迭代都可以产生.复杂度都可以为O(2n*合法的括号组合数),即每次产生出的括号序列都保证是合法的. ...

  8. 22.Generate Parentheses[M]括号生成

    题目 Given n pairs of parentheses, write a function to generate all combinations of well-formed parent ...

  9. [LeetCode] Valid Parentheses 验证括号

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

随机推荐

  1. 关于css清除浮动,解决内容溢出的问题

    以前在布局的时候总会遇到这样的问题,比如我想让整体的内容居中,所以会这样写, .main-content{ width:960px:height:300px;margin:0px auto; } 然后 ...

  2. CloudNotes之领域建模篇:领域模型简介

    CloudNotes领域模型还是相对简单的,并不一定需要采用面向领域驱动的设计方法来解决CloudNotes的领域问题.但出于以下几个方面的原因,我还是采用了面向领域驱动的方式来开发CloudNote ...

  3. scikit-learn一般实例之四:管道的使用:链接一个主成分分析和Logistic回归

    主成分分析(PCA)进行无监督的降维,而逻辑回归进行预测. 我们使用GridSearchCV来设置PCA的维度 # coding:utf-8 from pylab import * import nu ...

  4. 使用WampServer环境,如何配置虚拟主机域名

    很多人不会配置虚拟主机,我这里简单交一下大家,分三步: 1.在 C:\Windows\System32\drivers\etc 文件夹中的文件 Hosts 文件修改代码为: 127.0.0.1 loc ...

  5. Servlet 服务器性能提高--->数据库请求频率控制(原创)

    首先我要说下我实现这个功能接口涉及到的业务和实现的详细流程,然后会说此接口涉及到的相关技术,最后会贴出注释后的详细代码, 这个接口涉及到的是 app上咻一咻功能,咻一咻中奖的奖品一共有七类,其中四类是 ...

  6. 如何在ASP.NET Web站点中统一页面布局[Creating a Consistent Layout in ASP.NET Web Pages(Razor) Sites]

    如何在ASP.NET Web站点中统一页面布局[Creating a Consistent Layout in ASP.NET Web Pages(Razor) Sites] 一.布局页面介绍[Abo ...

  7. [连载]《C#通讯(串口和网络)框架的设计与实现》- 8.总体控制器的设计

    目       录 第八章           总体控制器的设计... 2 8.1           总控制器的职能... 2 8.2           组装和释放部件... 3 8.3      ...

  8. 块级标签包含行内标签底部出现3px间隔的解决办法

    当块级标签(如div)内包含了行内标签(如img),则外层元素与内层元素底部会出现3px的间隔: 代码如下: <!doctype html> <html lang="en& ...

  9. 关于JS交互--调用h5页面,点击页面的按钮,分享到微信朋友圈,好友

    关于js交互,在iOS中自然就想到了调用代理方法 另外就是下面的,直接上代码了: 如果你的后台需要知道你的分享结果,那么,就在回调里面调用上传到服务器结果的请求即可

  10. Linux-学习前言

    本随笔会持续,不定期更新.我有上网找与Linux相关的博客,发现很多人只写了几篇就没更新了,没有坚持下来!希望我能keep  on. 最近一个月是考试月,可能更新会比较少.