20:判断括号序列合法性--利用栈
利用栈作为辅助数据结构。注意:C++中char变量要用单引号'(' ,"("是字符串,即 char [2]
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> dict;
dict.insert(pair<char, char>('(', ')')); //开始使用"(",报错显示char[2]数组,C++中char单字符要用''表示,""包含的是字符串
dict.insert(unordered_map<char, char>::value_type('[', ']'));
dict['{'] = '}';
stack<char> stack_c;
for(int i=0; i<s.size(); i++) {
//遇到左括号,入栈
if(dict.find(s[i]) != dict.end()) {
stack_c.push(s[i]);
}
//遇到右括号,判断
else {
if(stack_c.empty()) return false;
if(s[i] != dict[stack_c.top()]) return false;
stack_c.pop();
}
}
if(!stack_c.empty()) return false;
return true;
}
};
Python3实现
class Solution:
def isValid(self, s: str) -> bool:
Dict = {'{':'}', '(':')', '[':']'}
stack_c = []
#label = False
for item in s:
if item in Dict:
stack_c.append(item)
if item in Dict.values():
if len(stack_c) == 0:
return False
if Dict[stack_c[-1]] != item:
return False
stack_c.pop()
if len(stack_c) != 0:
return False
return True
22:生成所有的合法括号序列-回溯法、闭合法
回溯法(即DFS)
class Solution {
public:
vector<string> generateParenthesis(int n) {
string s = "";
backtrack(s, n, 0, 0);
return res;
}
void backtrack(string s, int n, int left, int right) { //因为是回溯法,递归返回时要恢复到当时的s的状态,因此不能用引用
if(s.length() == n * 2) {
res.push_back(s);
return;
}
if(left < n) {
//s = s + "(";
backtrack(s + "(", n, left+1, right); //要保证该分支遍历完返回时s不变
}
if(right < left) {
//s = s + ")";
backtrack(s + ")", n, left, right+1);
}
}
private:
vector<string> res;
};
class Solution {
public:
vector<string> generateParenthesis(int n) {
string s = "";
dfs(s, n, n, n);
return res;
}
void dfs(string s, int n, int left, int right) {
if(s.length() == 2 * n) {
res.push_back(s);
}
if(left > right) return; //回溯的隐形树剪枝
if(left > 0) dfs(s+"(", n, left-1, right);
if(right > 0) dfs(s+")", n, left, right-1);
}
private:
vector<string> res;
};
动态规划方法:
class Solution {
public:
vector<string> generateParenthesis(int n) {
if(n == 0) return {};
if(n == 1) return {"()"};
vector<vector<string>> dp(n+1); //dp每个元素都是一个集合:代表i对括号时所有的可能序列
dp[0] = {""};
dp[1] = {"()"};
for(int i = 2; i <= n; i++) {
for(int j = 0; j < i; j++) {
for(string p : dp[j]) {
for(string q : dp[i-j-1]) {
string str = "(" + p + ")" + q;
dp[i].push_back(str);
}
}
}
}
return dp[n];
}
};