921. 使括号有效的最少添加

代码实现(模拟)
class Solution {
public:
int minAddToMakeValid(string s) {
int count = 0;
int ans = 0;
bool usedRight = false;
for (char c : s) {
if (c == '(') {
count++;
}
else {
if (count) {
count--;
}
else ans++;
}
}
return ans + count;
}
};
971. 翻转二叉树以匹配先序遍历

代码实现(先序遍历)
class Solution {
private:
vector<int> voyage;
vector<int> ans;
void match(TreeNode* root, int& pos) {
if (!root->left && !root->right) return;
if (root->left) {
if (root->left->val == voyage[pos]) {
pos += 1;
match(root->left, pos);
}
else if (root->right && root->right->val == voyage[pos]){
ans.push_back(root->val);
swap(root->left, root->right);
pos += 1;
match(root->left, pos);
}
else return;
if (!root->right || root->right->val != voyage[pos]) return;
pos += 1;
match(root->right, pos);
}
else {
if (root->right->val != voyage[pos]) return;
pos += 1;
match(root->right, pos);
}
}
public:
vector<int> flipMatchVoyage(TreeNode* root, vector<int>& voyage) {
if (root->val != voyage[0]) return {-1};
this->voyage = voyage;
int pos = 1;
match(root, pos);
vector<int> d = {-1};
return pos == voyage.size() ? ans : d;
}
};
1312. 让字符串成为回文串的最少插入次数

代码实现(dp)
class Solution {
public:
int minInsertions(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
for (int i = n - 2; i >= 0; i--) {
for (int j = i + 1; j < n; j++) {
if (s[i] == s[j]) dp[i][j] = dp[i + 1][j - 1];
else dp[i][j] = min(dp[i][j - 1], dp[i + 1][j]) + 1;
}
}
return dp[0][n - 1];
}
};