20. Valid Parentheses合法括号
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
分析:本题构造一个栈,open括号进栈,close括号检查栈是否非空且栈顶元素为对应的open符号,否则返回false,结束后若栈空返回true。
class Solution {
public:
bool isValid(string s) {
int l = s.size();
stack<char> st;
for(int i=0;i<l;i++)
{
char c = s[i];
if(c=='(' || c=='[' || c=='{')
st.push(c);
else
{
if(st.empty())
return false;
if(c==')')
if(st.top() == '(')
st.pop();
else
return false;
else if(c==']')
if(st.top() == '[')
st.pop();
else
return false;
else if(c=='}')
if(st.top() == '{')
st.pop();
else
return false;
}
}
if(st.empty())
return true;
return false;
}
};
22. 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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
分析:本题可使用回溯法解决,回溯法其实就是DFS加剪枝,这里我们添加两个剪枝条件:
1.先尝试添加左括号,如果左括号数目小于n
2.再尝试添加右括号数目,如果右括号数目小于当前左括号数目
所以我们的回溯函数有五个参数,分别为:ans,当前string,left数目,right数目,n
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
backtrack(ans,"",0,0,n);
return ans;
}
void backtrack(vector<string> &ans, string cur, int left, int right,int max)
{
if(cur.size()==max*2)
{
ans.push_back(cur);
return;
}
if(left<max)
backtrack(ans,cur+'(',left+1,right,max);
if(right<left)
backtrack(ans,cur+')',left,right+1,max);
}
};