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);
}
};