generate-parentheses
来源:互联网 发布:java 线程面试题 编辑:程序博客网 时间:2024/06/01 07:24
题目:
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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
程序:
class Solution {public: vector<string> generateParenthesis(int n) { string s; set<string> temp;//去重 vector<string> res; stack<char> st; for (int i = 0; i < n; i++) s = s + "()"; sort(s.begin(), s.end());//使用next_permutation之前需要进行排序处理,否则个数会减少 do { temp.insert(s); } while (next_permutation(s.begin(), s.end())); for (auto it = temp.begin(); it != temp.end(); ++it) { string ss = *it; int i = 0; for (; i < ss.size(); i++) { if (ss[i] == '(') st.push(')'); else if (st.empty()) break; else { st.pop(); } } if (i == ss.size()) res.push_back(ss); } return res; }};
点评:
在next_permutation之前必须要排序,采用set去重,这题主要采用排列组合的思想,先把所有可能列出,然后在剔除。
阅读全文
0 0
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- Generate Parentheses
- 在线速查手册。
- UVa 725 Division(暴力求解)
- git config
- 静态的html页面想要设置使用浏览器缓存
- Python 网络编程(套接字编程)
- generate-parentheses
- 使用 Git Bash 配置用户名和命令别名
- (Android网络4)Retrofit
- HDOJ HDU 1048 The Hardest Problem Ever
- <meta http-equiv="pragma" content="no-cache">属性http-equiv功能介绍
- eclipse下的UML妙用
- java String
- TCP和UDP的详细区别
- 动态广播注册源码分析