Generate Parentheses
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
参考:
http://www.cnblogs.com/remlostime/archive/2012/11/06/2757711.html
http://www.2cto.com/kf/201310/251552.html
http://blog.youkuaiyun.com/pickless/article/details/9141935
class Solution {
public:
vector<string> generateParenthesis(int n) {
string str;
vector<string> ret;
generateParenthesisCore(ret,"",0,0,n);
return ret;
}
void generateParenthesisCore(vector<string> &ret,string str,int lnum,int rnum,const int n)
{
if(lnum > n) return;
if(lnum + rnum == 2*n)
ret.push_back(str);
generateParenthesisCore(ret,str+'(',lnum + 1,rnum,n);
if(lnum > rnum)
generateParenthesisCore(ret,str+')',lnum,rnum+1,n);
}
};
Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
class Solution {
public:
bool isValid(string s) {
int size = s.size();
stack<char> stk;
while(size--)
{
if(stk.size() == 0 || !ispair(stk.top(),s[size]))
stk.push(s[size]);
else
stk.pop();
}
return stk.empty();
}
bool ispair(char ch1,char ch2)
{
return ((ch1 == ')' && ch2 == '(')||(ch1 == '}' && ch2 == '{')||(ch1 == ']' && ch2 == '[')) ;
}
};