思路:选取字符和不选取字符
但是TLE了
需要加以下内容剪枝
if (i != idx && s[i] == s[i - 1]) continue;//该行可以避免同一层选取同样的字符
int c1 = 0, c2 = 0, c3 = 0;//c1是(总数,c2是)总数,c3是字母总数
if (cnt > c2) return;//cnt代表还需要匹配的(数,即)数目不够
if (!ans.empty() && path.size() + (n - idx) < ans[0].size()) return;//path和idx之后的都能匹配也小于最长长度
此外会有重复的path,需要标记下path
if (mp.find(path) != mp.end()) return;
#include <unordered_map>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @return string字符串vector
*/
unordered_map<string, int>mp;
int c1 = 0, c2 = 0, c3 = 0;//c1是(总数,c2是)总数,c3是字母总数
void dfs(string& s, vector<string>& ans, string path, int idx, int cnt,
int& n) {
if (cnt < 0) return;
if (cnt > c2) return;//cnt代表还需要匹配的(数
if (!ans.empty() && path.size() + (n - idx) < ans[0].size()) return;
if (idx == n) {
if (path.size() < c3) return;
if (cnt || mp.find(path) != mp.end()) return;
if (ans.empty() || ans[0].size() < path.size()) {
ans.clear();
ans.push_back(path);
mp[path] = 1;
} else if (ans[0].size() == path.size() ) {
if (mp.find(path) != mp.end()) return;
else mp[path] = 1;
ans.push_back(path);
}
return;
}
for (int i = idx; i < n; i++) {
if (i != idx && s[i] == s[i - 1]) continue;//该行可以避免同一层选取同样的字符
dfs(s, ans, path, i + 1, cnt, n);
char tmp = s[i];
string path2 = "";
switch (tmp) {
case '(':
path2 = path + "(" ;
dfs(s, ans, path2, i + 1, cnt + 1, n);
break;
case ')':
if (cnt > 0) {
path2 = path + ")";
dfs(s, ans, path2, i + 1, cnt - 1, n);
}
break;
default:
if (cnt < 0) return;
path2 = path + tmp;
dfs(s, ans, path2, i + 1, cnt, n);
break;
}
}
}
vector<string> maxValidParenthesesStr(string s) {
// write code here
int n = s.size();
if (n < 2) return {""};
for (int i = 0; i < n; i++) {
if (s[i] == '(')
c1++;
else if (s[i] == ')')
c2++;
else c3++;
}
vector<string> ans;
string path;
dfs(s, ans, path, 0, 0, n);
return ans;
}
};