第一题暴力法。我用java写爆内存 AC了90%
import java.util.Scanner;
public class Main {
static int sum = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
if (s == null || s.length() <= 0)
System.out.println(0);
else {
count(s);
System.out.println(sum);
}
in.close();
}
public static void count(String str) {
if ("".equals(str) || "()".equals(str)) {
sum++;
return;
}
char[] tmp = str.toCharArray();
for (int i = tmp.length - 1; i > 0; i--) {
if (tmp[i] == ')' && isK(tmp, i)) {
String st = "";
String st2 = "";
if (i > 1)
st = new String(tmp, 1, i - 1);
if (i < str.length())
st2 = str.substring(i + 1, str.length());
String next = st + st2;
if ("()".equals(next) || "".equals(next)) {
sum++;
continue;
}
count(next);
}
}
}
public static boolean isK(char[] str, int s) {
int lef = 0, rig = 0;
for (int i = 1; i < str.length; i++) {
if (i == s)
continue;
if (str[i] == '(')
lef++;
else if (str[i] == ')')
rig++;
}
if (lef == rig)
return true;
return false;
}
}