乘风破浪:LeetCode真题_022_Generate Parentheses

一、前言

关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比较方便。

二、Generate Parentheses

2.1 问题

2.2 分析与解决

    既然用递归就要构造模型,这里我们定义left和right分别代表剩余的左右括号的数目,如果出现了left>right,那么就会出现实际上的左括号小于右括号的结果,出现错误,如果剩余都小于零就结束,只有都剩余为0的时候才记录,这样我们就得到了结果。

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);
}
}

    那么官方是怎么说的呢?

class Solution {
public List<String> generateParenthesis(int n) {
List<String> combinations = new ArrayList();
generateAll(new char[2 * n], 0, combinations);
return combinations;
} public void generateAll(char[] current, int pos, List<String> result) {
if (pos == current.length) {
if (valid(current))
result.add(new String(current));
} else {
current[pos] = '(';
generateAll(current, pos+1, result);
current[pos] = ')';
generateAll(current, pos+1, result);
}
} public boolean valid(char[] current) {
int balance = 0;
for (char c: current) {
if (c == '(') balance++;
else balance--;
if (balance < 0) return false;
}
return (balance == 0);
}
}

也是用了一种递归的方法,先生成左括号,再递归,直至遍历完所有的情况,因此复杂度非常的高,究其原因是没有考虑到一些本来就可以省略的情况。

    于是做出了改进,将一些情况进行了优化,只有右括号小于左括号的时候才能添加右括号,左括号也不能超过最大的上限:

class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList();
backtrack(ans, "", 0, 0, n);
return ans;
} public void backtrack(List<String> ans, String cur, int open, int close, int max){
if (cur.length() == max * 2) {
ans.add(cur);
return;
} if (open < max)
backtrack(ans, cur+"(", open+1, close, max);
if (close < open)
backtrack(ans, cur+")", open, close+1, max);
}
}

三、总结

这一题其实是比较难的,因为我们可能无从下手,就算用递归的时候也不能抓住要害,因此如何定义递归中变量的含义至关重要。

乘风破浪:LeetCode真题_022_Generate Parentheses的更多相关文章

  1. 乘风破浪:LeetCode真题_020_Valid Parentheses

    乘风破浪:LeetCode真题_020_Valid Parentheses 一.前言 下面开始堆栈方面的问题了,堆栈的操作基本上有压栈,出栈,判断栈空等等,虽然很简单,但是非常有意义. 二.Valid ...

  2. 乘风破浪:LeetCode真题_032_Longest Valid Parentheses

    乘风破浪:LeetCode真题_032_Longest Valid Parentheses 一.前言 这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次 ...

  3. 乘风破浪:LeetCode真题_041_First Missing Positive

    乘风破浪:LeetCode真题_041_First Missing Positive 一.前言 这次的题目之所以说是难,其实还是在于对于某些空间和时间的限制. 二.First Missing Posi ...

  4. 乘风破浪:LeetCode真题_040_Combination Sum II

    乘风破浪:LeetCode真题_040_Combination Sum II 一.前言 这次和上次的区别是元素不能重复使用了,这也简单,每一次去掉使用过的元素即可. 二.Combination Sum ...

  5. 乘风破浪:LeetCode真题_039_Combination Sum

    乘风破浪:LeetCode真题_039_Combination Sum 一.前言     这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标. 二.Combination Sum ...

  6. 乘风破浪:LeetCode真题_038_Count and Say

    乘风破浪:LeetCode真题_038_Count and Say 一.前言     这一道题目,很类似于小学的问题,但是如果硬是要将输入和结果产生数值上的联系就会产生混乱了,因此我们要打破思维定势. ...

  7. 乘风破浪:LeetCode真题_037_Sudoku Solver

    乘风破浪:LeetCode真题_037_Sudoku Solver 一.前言 这次我们对于上次的模型做一个扩展并求解. 二.Sudoku Solver 2.1 问题 2.2 分析与解决     这道题 ...

  8. 乘风破浪:LeetCode真题_036_Valid Sudoku

    乘风破浪:LeetCode真题_036_Valid Sudoku 一.前言 有的时候对于一些基础知识的掌握,对我们是至关重要的,比如ASCII重要字符的表示,比如一些基本类型的长度. 二.Valid ...

  9. 乘风破浪:LeetCode真题_035_Search Insert Position

    乘风破浪:LeetCode真题_035_Search Insert Position 一.前言 这次的问题比较简单,也没有限制时间复杂度,但是要注意一些细节上的问题. 二.Search Insert ...

随机推荐

  1. com.alibaba.fastjson.JSON对类对象的序列化与反序列化

    1. 目标 把类的对象存储到字符串可存储 2. 类定义 public interface JsonInterface { } mport com.alibaba.fastjson.JSON; impo ...

  2. Quartz框架多个trigger任务执行出现漏执行的问题分析--转

    原文地址:http://blog.csdn.net/dailywater/article/details/51470779 一.问题描述 使用Quartz配置定时任务,配置了超过10个定时任务,这些定 ...

  3. 跨站点请求伪造(CSRF)

    一.前言 跨站点请求伪造(Cross-SiteRequest Forgeries, CSRF),是指攻击者通过设置好的陷阱,强制对已完成认证的用户进行非预期的个人信息或设定信息等某些状态更新,属于被动 ...

  4. Spring基础(9) : 自动扫描

    一  配置xml方式:扫描com包下的bean <?xml version="1.0" encoding="UTF-8" ?> <beans ...

  5. Vue之组件使用(一)

    这仅仅是个人为了防止忘记做的笔记而已,仅供参考,有不对的地方请纠正 组件这种东西用来封装多次使用的控件还是很有用处的,我还是挺喜欢这种模式,优化了前端的工作,写个组件也比较简单.下次有时间记录一下样式 ...

  6. 面向对象设计模式_生成器模式解读(Builder Pattern)

    首先提出一个很容易想到应用场景: 手机的生产过程:手机有非常多的子件(部件),成千上万,不同品牌的手机的生产过程都是复杂而有所区别的,相同品牌的手机在设计上也因客户需求多样化,大到型号,小到颜色,是否 ...

  7. LOJ1070(SummerTrainingDay05-B 矩阵快速幂)

    Algebraic Problem Given the value of a+b and ab you will have to find the value of an+bn. a and bnot ...

  8. <Android 基础(三 十)> Fragment (3) ~ PreferenceFragment

    简介 PreferenceFragment , 展示一系列的Preference条目并且当与用户有交互时,产生的值会自动保存到SharedPreferences中,通过PreferenceManage ...

  9. Memcached+WebApi记录

    一.安装Memcached Memcached1.2.6 http://files.cnblogs.com/files/jasonduan/11465401756756.zip Memcached.C ...

  10. SQLServer 2005客户端远程连接sql2008 数据库服务器

    SQL2005客户端远程连接sql2008 数据库服务器 by:授客 QQ:1033553122 准备工作: 客户端所在pc机配置: 配置数据源 控制面板-管理工具-ODBC数据源-系统DSN-添加- ...