Question

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:

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

Solution 1

Two conditions to check:

if remained left '(' nums < remained right ')', for next char, we can put '(' or ')'.

if remained left '(' nums = remained right ')', for next char, we can only put '('.

Draw out the solution tree, and do DFS.

 public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
List<Character> list = new ArrayList<Character>();
dfs(n, n, list, result);
return result;
} private void dfs(int leftRemain, int rightRemain, List<Character> list, List<String> result) {
if (leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain)
return; if (leftRemain == 0 && rightRemain == 0) {
int size = list.size();
StringBuilder sb = new StringBuilder(size);
for (char tmpChar : list)
sb.append(tmpChar);
result.add(sb.toString());
return;
} if (leftRemain == rightRemain) {
list.add('(');
dfs(leftRemain - 1, rightRemain, list, result);
list.remove(list.size() - 1);
} else {
list.add(')');
dfs(leftRemain, rightRemain - 1, list, result);
list.remove(list.size() - 1);
list.add('(');
dfs(leftRemain - 1, rightRemain, list, result);
list.remove(list.size() - 1);
}
}
}

Solution 2

A much simpler solution.

 public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
List<Character> list = new ArrayList<Character>();
dfs(n, n, "", result);
return result;
} private void dfs(int leftRemain, int rightRemain, String prefix, List<String> result) {
if (leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain)
return;
if (leftRemain == 0 && rightRemain == 0) {
result.add(new String(prefix));
return;
}
if (leftRemain > 0)
dfs(leftRemain - 1, rightRemain, prefix + "(", result);
if (rightRemain > 0)
dfs(leftRemain, rightRemain - 1, prefix + ")", result);
}
}

Generate Parentheses 解答的更多相关文章

  1. Generate Parentheses - LeetCode

    目录 题目链接 注意点 解法 小结 题目链接 Generate Parentheses - LeetCode 注意点 解法 解法一:递归.当left>right的时候返回(为了防止出现 )( ) ...

  2. 72. Generate Parentheses && Valid Parentheses

    Generate Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...

  3. Generate Parentheses

    Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of ...

  4. [LintCode] Generate Parentheses 生成括号

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

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

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

  6. 【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses

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

  7. leetcode022. Generate Parentheses

    leetcode 022. Generate Parentheses Concise recursive C++ solution class Solution { public: vector< ...

  8. [Leetcode][Python]22: Generate Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 22: Generate Parentheseshttps://oj.leet ...

  9. N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法

    回溯法 百度百科:回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步又一次选择,这样的走不通就退回再走的技术为回溯法 ...

随机推荐

  1. c++ 14

    一.堆栈(stack) stack -> vector/deque/list push  -> push_back pop   -> pop_back top   -> bac ...

  2. Makefile中使用foreach生成一类规则

    CSDN上,有朋友发帖问了这样一个问题(我按自己的理解翻译一下): 当前目录下有四个静态库文件:  liba.a libb.a libc.a libd.a.现在想将它们做成一个动态库libp.so. ...

  3. 【Cocos2d-X游戏实战开发】捕鱼达人之游戏场景的创建(六)

    本系列学习教程使用的是cocos2d-x-2.1.4(最新版为cocos2d-x-2.1.5)    博主发现前两个系列的学习教程被严重抄袭,在这里呼吁大家请尊重开发者的劳动成果, 转载的时候请务必注 ...

  4. RAID,mdadm(笔记)

    RAID: 级别:仅代表磁盘组织方式不同,没有上下之分:0: 条带    性能提升: 读,写    冗余能力(容错能力): 无    空间利用率:nS    至少2块盘1: 镜像    性能表现:写性 ...

  5. 学艺不精,又被shell的管道给坑了

    我用过bash shell,而且时间不短了.但我从来没学过shell,至少没有像C++这么认真去学.平时写些基本的脚本没问题,不懂也可以google.百度.可在2014最后一天,掉坑里了. 其实脚本也 ...

  6. 《招聘一个靠谱的iOS》面试题参考答案(下)

    相关文章: <招聘一个靠谱的iOS>面试题参考答案(上) 说明:面试题来源是微博@我就叫Sunny怎么了的这篇博文:<招聘一个靠谱的 iOS>,其中共55题,除第一题为纠错题外 ...

  7. Linux安装中文man手冊

    1.下载中文包: http://pkgs.fedoraproject.org/repo/pkgs/man-pages-zh-CN/manpages-zh-1.5.1.tar.gz/13275fd039 ...

  8. HTTP协议5之代理--转

    代理服务器 Web代理(proxy)服务器是网络的中间实体. 代理位于Web客户端和Web服务器之间,扮演“中间人”的角色. HTTP的代理服务器即是Web服务器又是Web客户端. Fiddler就是 ...

  9. HTTP协议1之协议详解--转

    当今web程序的开发技术真是百家争鸣,ASP.NET, PHP, JSP,Perl, AJAX 等等. 无论Web技术在未来如何发展,理解Web程序之间通信的基本协议相当重要, 因为它让我们理解了We ...

  10. sqlserver2008 中使用MSXML2.ServerXMLHttp拼装soap调用webservice

    要调用的接口方法:UP_ACC_inst_Info(string xml) 接口参数:xml格式的字符串 接口功能:传递人员编号.备注到接口进行更新,接口返回更新结果. 实例: declare @st ...