Generate Parentheses
来源:互联网 发布:淘宝助理订单下载 编辑:程序博客网 时间:2024/06/08 10:01
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> res; vector<string> generateParenthesis(int n) { generateParenthesis(n,"",stack<int>()); return res; } void generateParenthesis(int n,string s,stack<int> st) { if(n==0) { while(!st.empty()) { s=s+")"; st.pop(); } res.push_back(s); return ; } if(st.empty()) { st.push(1); generateParenthesis(n-1,s+"(",st); } else { st.push(1); generateParenthesis(n-1,s+"(",st); st.pop(); st.pop(); generateParenthesis(n,s+")",st); } }};
但其实并不非要有一个栈,我们所需要的只是当时栈中所剩元素的个数以及剩余没油入栈的元素个数,因此只需要两个计数器就可以。
class Solution {public: vector<string> generateParenthesis(int n) { vector<string> res; addingpar(res, "", n, 0); return res; } void addingpar(vector<string> &v, string str, int n, int m){ if(n==0 && m==0) { v.push_back(str); return; } if(m > 0){ addingpar(v, str+")", n, m-1); } if(n > 0){ addingpar(v, str+"(", n-1, m+1); } }};
看到评论区还有用DP做的,也贴上来好了
DP. First consider how to get the result f(n) from previous result f(0)…f(n-1). Actually, the result f(n) will be put an extra () pair to f(n-1). Let the “(” always at the first position, to produce a valid result, we can only put “)” in a way that there will be i pairs () inside the extra () and n - 1 - i pairs () outside the extra pair.
Let us consider an example to get clear view:
f(0): “”
f(1): “(“f(0)”)”
f(2): “(“f(0)”)”f(1), “(“f(1)”)”
f(3): “(“f(0)”)”f(2), “(“f(1)”)”f(1), “(“f(2)”)”
So f(n) = “(“f(0)”)”f(n-1) , “(“f(1)”)”f(n-2) “(“f(2)”)”f(n-3) … “(“f(i)”)”f(n-1-i) … “(f(n-1)”)”
- 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
- docker php环境容器大瘦身
- 中英文维基百科语料上的Word2Vec实验
- steam段错误
- java集合-笔记
- Java --- 读写文件操作
- Generate Parentheses
- java多线程-笔记
- 【scrapyd】windows下安装运行scrapyd
- CoordinatorLayout 的jar包位置
- php日常3-21 设计一个九九乘法表
- POJ3126Prime Path(BFS)
- hadoop命令及hive数据库操作语句的简单使用
- 【实例】ajax提交到java后台之后处理数据
- leetcode——292—— Nim Game