lintcode,生成括号
来源:互联网 发布:淘宝阿迪旗舰店是正品 编辑:程序博客网 时间:2024/05/17 01:49
给定 n 对括号,请写一个函数以将其生成新的括号组合,并返回所有组合结果。
样例
给定 n = 3, 可生成的组合如下:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
一刷没ac
解题思路:类似dp的思想,考虑n个括号是有n-1生成来的,相当于将所有n-1拆为两部分,再加入一个括号。也可以在n-1的基础上每个可能的位置都插入一个括号。
public class Solution { /** * @param n n pairs * @return All combinations of well-formed parentheses */ public ArrayList<String> generateParenthesis(int n) { ArrayList<String> res = new ArrayList<String>(); if(n == 0) { res.add(""); return res; } for(int i = 0; i < n; i++){ ArrayList<String> head = generateParenthesis(i); ArrayList<String> tail = generateParenthesis(n-1-i); for(String strhead : head){ for(String strtail : tail){ res.add("("+strhead+")"+strtail); } } } return res; }}
public class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<String>(); if(n < 1) return res; if(n == 1){ res.add("()"); return res; } List<String> pre = generateParenthesis(n-1); HashSet<String> set = new HashSet<String>(); for(int i = 0; i < pre.size(); i++){ String str = pre.get(i); for(int j = 0; j <= str.length(); j++){ String first = str.substring(0, j); String last = str.substring(j, str.length()); set.add(first+"()"+last); } } for(String s : set){ res.add(s); } return res; }}
0 0
- LintCode : 生成括号
- LintCode-生成括号
- LintCode:生成括号
- LintCode:生成括号
- lintcode,生成括号
- 生成括号-lintcode
- lintcode -- 生成括号
- LintCode 生成括号
- DFS-lintcode生成括号
- 生成括号-LintCode
- lintcode刷题--生成括号
- lintcode--生成括号
- [Lintcode]Generate Parentheses 生成括号
- Generate Parentheses 生成括号-- LintCode题解
- lintcode括号匹配
- 生成括号
- 生成括号
- 生成括号
- 点评 ibatis+oracle 批量插入的三种方法
- linux date -d参数用法
- 强大的Spring缓存技术(中)
- 属性ID
- 打开WPF设计器提示错误未能从程序集 “Microsoft.Expression.DesignModel”.....
- lintcode,生成括号
- Linux下出现Read-only file system的解决办法
- 介绍10 款最好的 Python IDE
- Android控件显示/隐藏时添加动画:ViewSwitcher
- Activity启动过程源码分析
- 在自动驾驶中,单线激光雷达能干什么?
- 解决“只能通过Chrome网上应用商店安装该程序”的方法
- sql 删除重复数据
- tomcat+https协议的接口编写及客户端访问