Generate Parentheses 解答
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 解答的更多相关文章
- Generate Parentheses - LeetCode
目录 题目链接 注意点 解法 小结 题目链接 Generate Parentheses - LeetCode 注意点 解法 解法一:递归.当left>right的时候返回(为了防止出现 )( ) ...
- 72. Generate Parentheses && Valid Parentheses
Generate Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...
- Generate Parentheses
Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of ...
- [LintCode] Generate Parentheses 生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- [CareerCup] 9.6 Generate Parentheses 生成括号
9.6 Implement an algorithm to print all valid (e.g., properly opened and closed) combinations of n-p ...
- 【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- leetcode022. Generate Parentheses
leetcode 022. Generate Parentheses Concise recursive C++ solution class Solution { public: vector< ...
- [Leetcode][Python]22: Generate Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 22: Generate Parentheseshttps://oj.leet ...
- N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法
回溯法 百度百科:回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达到目标.但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步又一次选择,这样的走不通就退回再走的技术为回溯法 ...
随机推荐
- thinkpad t530 centos 6.4 有线网卡 设置
由于新装的系统没有安装网卡驱动,各大厂商的标准又不一样,有的电脑在linux下不用安装无线网卡驱动,而很不幸,我的电脑是ret的网卡,只能自行安装,在安装无线网卡的过程中使用到了chkconfig的命 ...
- 选择排序(Selection Sort)
选择排序就是在选择数组元素上做文章,关键是如何选择?选择的标准是什么?选择之后放在哪?所有这些都是选择排序的问题. 选择排序算法中,通常会有以下操作: 从数组第一个元素开始. 遍历整个数组,找到最小的 ...
- IOS开发错误提示原因集合-----长期更新
"[__NSCFConstantString size]: unrecognized selector sent to instance." =>将NSString类型的参数 ...
- linux下面测试网络带宽 (转载)
利用bmon/nload/iftop/vnstat/iptraf实时查看网络带宽状况 一.添加yum源方便安装bmon# rpm -Uhv http://apt.sw.be/redhat/el5/en ...
- JVM结构、GC工作机制详解
JVM结构.内存分配.垃圾回收算法.垃圾收集器.下面我们一一来看. 一.JVM结构 根据<java虚拟机规范>规定,JVM的基本结构一般如下图所示: 从左图可知,JVM主要包括四个部分 ...
- shadow projection
1.概述 shadow projection,又可成为planar shadow, 这是一种非常简单的绘制阴影的方法. 主要应用的应用场景:物体在平面投射阴影. 主要思想:把阴影看作是物体在平面上的投 ...
- OCP-1Z0-051-题目解析-第6题
6. Examine the structure of the SHIPMENTS table: name Null Type PO_ID ...
- hadoop多文件输出
现实环境中,经常遇到一个问题就是想使用多个Reduce,可是迫于setup和cleanup在每个Reduce中会调用一次,仅仅能设置一个Reduce,无法是实现负载均衡. 问题,假设要在reduce中 ...
- java 中Date的格式化样式
public static void main(String[] args) { Date d = new Date(); System.out.println(d); // Date类的默认格式 T ...
- JavaScript自我学习之解析与执行
如果想要学好JavaScript那么我们首先必须要知道浏览器JavaScript引擎是如何解释执行JavaScript代码的,作为一名菜鸟,从自己学习JavaScript的过程来说,真心觉得不了解这些 ...