leetcode 括號組合題目 20 是否是有效括號 32 最大有效括號 301 去掉無效括號
- class Solution {
- public:
- bool isValid(string s) {
- stack<char> result;
- for(auto & a:s){
- if(a=='(') result.push(')');
- elseif(a=='{') result.push('}');
- elseif(a=='[') result.push(']');
-
elseif(result.empty()||result.top()!=a)
- returnfalse;
- else result.pop();
- }
- return result.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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]查看回溯部分
32. Longest Valid Parentheses 最長有效括號組合
動態規劃:
-
s and s[i−1]=‘(’, i.e. string looks like ‘‘.......()"⇒
dp[i]=dp[i−2]+2
We do so because the ending "()" portion is a valid substring anyhow and leads to an increment of 2 in the length of the just previous valid substring's length.
-
s[i]=‘)’ and s[i−1]=‘)’, i.e. string looks like ‘‘.......))"⇒
if s[i−dp[i−1]−1]=‘(’ then
dp[i]=dp[i−1]+dp[i−dp[i−1]−2]+2
class Solution { public: int longestValidParentheses(string s) { int n=s.size(); if(n<=1) return 0; int res=0; vector<int> dp(n,0); if(s[0]=='('&&s[1]==')') { dp[1]=2; res=2; } for(int i=2;i<n;i++)//注意這裡並不是奇偶數的遍歷,因為不一定是奇數或者偶數為是有效的 { if(s[i]==')') { if(s[i-1]=='(') dp[i]=dp[i-2]+2; else if(s[i-1-dp[i-1]]=='(') dp[i]=dp[i-1]+dp[i-1-dp[i-1]-1]+2; } res=max(res,dp[i]); } return res; } };
方法3 棧 -
方法4 空間1 left right
public class Solution {
public int longestValidParentheses(String s) {
int left = 0, right = 0, maxlength = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * right);
} else if (right >= left) {
left = right = 0;
}
}
left = right = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * left);
} else if (left >= right) {
left = right = 0;
}
}
return maxlength;
}
}
301. Remove Invalid Parentheses
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses (
and )
.
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]