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. Windows下AndroidStudio 中使用Git(AndroidStudio项目于GitHub关联)

    前提条件 : 1. 安装 Git 客户端 下载链接 2. 有 GitHub 账号 (假设你已经有了一些git基础, 如果还一点都不会, 请去找其他加成学习) AndroidStudio项目发布到Git ...

  2. Linux 挂载光驱

    Linux的硬件设备都在/dev目录下,/dev/cdrom表示光驱,挂载方法如下: 1.挂载光驱 [root@oracle ~]# mount -t iso9660 /dev/cdrom /mnt/ ...

  3. 高仿qq聊天界面

    高仿qq聊天界面,给有需要的人,界面效果如下: 真心觉得做界面非常痛苦,给有需要的朋友. chat.xml <?xml version="1.0" encoding=&quo ...

  4. Qt之操作Excel

    Visual Basic for Applications(VBA)是一种Visual Basic的一种宏语言,主要能用来扩展Windows的应用程式功能,特别是Microsoft Office软件. ...

  5. android——混淆打包

    网上搜了一大堆,在此不一一赘诉. 直接讲解了 如上图这么配置,其实就是加上一句话而已.告诉打包工具混淆打包的代码放在./proguard-project.txt这里 proguard.config=. ...

  6. SQL日期形式转换

    在SQL Server中,有时存储在数据库中的日期格式和我们需要显示在页面上的格式不相同,我们需要转化成需要的格式. 特在此总结了一下常用的日期格式. --当前时间 SELECT GETDATE(); ...

  7. 浏览器的Storage做缓存需要注意的地方

    使用浏览器的Storage来做缓存.如: window.sessionStorage.setItem("cache", $(data).stringify()) 需要注意以下几点: ...

  8. 使用Spring JDBCTemplate简化JDBC的操作

    使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...

  9. block中无法使用C数组变量

    在Objective-C的block中无法使用C数组,即使我们不对C数组做任何改变,编译的时候也会报错: #include <stdio.h> int main() { const cha ...

  10. c++连接mysql数据库(使用mysql api方式,环境VS2013+MYSQL5.6)

    转载请注明出处,原文地址http://www.cnblogs.com/zenki-kong/p/4382657.html 刚开始写博客,博主还只是个大三汪,学艺不精,如有错误还请前辈指出(>^ω ...