[Leetcode-22]Generate Parentheses 生成圆括号
来源:互联网 发布:女朋友漂亮知乎 编辑:程序博客网 时间:2024/05/17 07:30
0. 题目概要
- 题目概要
- 分析
- AC代码
- Java AC代码
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()"]
输入n, 输出所有n个左右括号的括号序列。
1. 分析
2. AC代码
DFS方法记录了:
- 左括号个数
- 当前的”部分解”
class Solution {public: void help(int n, int x, int y, string now, vector<string> &answer){ if(y == n){ answer.push_back(now); return; } if(x < n){ help(n, x+1, y, now + "(", answer); } if(x > y){ help(n, x, y+1, now + ")", answer); } } vector<string> generateParenthesis(int n) { vector<string> answer; help(n, 0, 0, "", answer); return answer; }};
3. Java AC代码
Java回溯法:
public List<String> generateParenthesis(int n) { List<String> list = new ArrayList<String>(); backtrack(list, "", 0, 0, n); return list; } public void backtrack(List<String> list, String str, int open, int close, int max){ if(str.length() == max*2){ list.add(str); return; } if(open < max) backtrack(list, str+"(", open+1, close, max); if(close < open) backtrack(list, str+")", open, close+1, max); }
The idea here is to only add ‘(’ and ‘)’ that we know will guarantee us a solution (instead of adding 1 too many close). Once we add a ‘(’ we will then discard it and try a ‘)’ which can only close a valid ‘(‘. Each of these steps are recursively called.
阅读全文
0 0
- [Leetcode-22]Generate Parentheses 生成圆括号
- [leetcode]Generate Parentheses 生成圆括号 python实现
- LeetCode 22 Generate Parentheses(生成括号)
- LeetCode 22 Generate Parentheses(生成括号)
- LeetCode 22: Generate Parentheses
- [leetcode 22] Generate Parentheses
- LeetCode | #22 Generate Parentheses
- [Leetcode] 22- Generate Parentheses
- LeetCode 22 Generate Parentheses
- [LeetCode 22]Generate Parentheses
- leetcode 22 Generate Parentheses
- Leetcode 22 Generate Parentheses
- LeetCode 22 - Generate Parentheses
- Generate Parentheses - LeetCode 22
- leetcode 22 -- Generate Parentheses
- leetcode-22Generate Parentheses
- leetcode 22: Generate Parentheses
- Leetcode#22 Generate Parentheses
- 战马列队
- 287. Find the Duplicate Number / 142. Linked List Cycle II(Java)
- Java 4.0 java 引用数据类型之数组
- 007.Net基础教程之复杂数据类型
- 任意长度数字的加法
- [Leetcode-22]Generate Parentheses 生成圆括号
- MongoDB聚合篇
- 问题 E: QAQ & 君临天下 || 天行九歌||多校联萌(三)
- 聚类分析经典算法讲解及实现
- 线性求区间欧拉函数(顺便线性求区间内所有素数)(类似欧拉线性素数筛)
- 微调-模型
- ACM暑假集训日记 17.8.11
- BZOJ 2818 Gcd + spoj 4491(莫比乌斯反演 分块)
- POJ 3046 -- Ant Counting (动态规划)