#include #include #include #include #include #include using namespace std; /* Test to see if a string s is a correct bracket sequence. Use a deque like a stack -- if a character is an opening character, push it on the stack. If it is a closing character, check to see its opening character is on the stack. If so, pop it and continue. Otherwise, return false. */ int is_cbs(string &s) { deque stack; int i; for (i = 0; i < s.size(); i++) { if (s[i] == '(' || s[i] == '[') { stack.push_front(s[i]); } else if (s[i] == ')' || s[i] == ']') { if (stack.empty() || (s[i] == ')' && stack[0] != '(') || (s[i] == ']' && stack[0] != '[')) return 0; stack.pop_front(); } else return 0; } return stack.empty(); } int main(int argc, char **argv) { string s, tmp; int i, j, counter; if (argc != 2) { fprintf(stderr, "Usage a.out string\n"); exit(1); } s = argv[1]; counter = 0; /* Generate all non-empty subsets of S and test them. Count up the results. */ for (i = 1; i < (1 << s.size()); i++) { tmp = ""; for (j = 0; j < s.size(); j++) { if (i & (1 << j)) tmp.push_back(s[j]); } if (is_cbs(tmp)) counter++; } printf("%d\n", counter-1); exit(0); }