LeetCode-20、22:Valid、Generate Parentheses(括號匹配、生成)
阿新 • • 發佈:2018-12-31
題目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
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
問題解析:
給定一個只包括 ‘(‘,’)’,’{‘,’}’,’[‘,’]’ 的字串,判斷字串是否有效。
連結:
思路標籤
演算法:棧結構
解答:
- 利用棧是否為空或者右符號是否能和棧頂配對來進行判斷。
class Solution {
public:
bool isValid(string s) {
stack<char> paren;
for (char& c : s) {
switch (c) {
case '(':
case '{':
case '[': paren.push(c); break;
case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;
case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
default: ; // pass
}
}
return paren.empty() ;
}
};
題目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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
問題解析:
給出 n 代表生成括號的對數,請你寫出一個函式,使其能夠生成所有可能的並且有效的括號組合。
連結:
思路標籤
演算法:遞迴、DFS
解答:
- 根據題目規則我們能夠知道,符號只有兩種“(”和“)”,我們分別記為其個數為左括號left和右括號right,所以滿足條件的組合一定是left<=right。否則,不符合要求。
- 同時,當left和right都為0時,當前組合滿足條件。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
generateParenthesisDFS(n, n, "", res);
return res;
}
void generateParenthesisDFS(int left, int right, string out, vector<string> &res){
if(left > right)
return;
if(left == 0 && right == 0)
res.push_back(out);
else{
if(left > 0) generateParenthesisDFS(left-1, right, out+'(', res);
if(right > 0) generateParenthesisDFS(left, right-1, out+')', res);
}
}
};
題目: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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
問題解析:
給出 n 代表生成括號的對數,請你寫出一個函式,使其能夠生成所有可能的並且有效的括號組合。
連結:
思路標籤
演算法:遞迴、DFS
解答:
- 根據題目規則我們能夠知道,符號只有兩種“(”和“)”,我們分別記為其個數為左括號left和右括號right,所以滿足條件的組合一定是left<=right。否則,不符合要求。
- 同時,當left和right都為0時,當前組合滿足條件。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
generateParenthesisDFS(n, n, "", res);
return res;
}
void generateParenthesisDFS(int left, int right, string out, vector<string> &res){
if(left > right)
return;
if(left == 0 && right == 0)
res.push_back(out);
else{
if(left > 0) generateParenthesisDFS(left-1, right, out+'(', res);
if(right > 0) generateParenthesisDFS(left, right-1, out+')', res);
}
}
};