▶ 问题:给定正整数 n,求由 n 对小括号组成的所有合法表达式,显然所求表达式的个数为卡塔兰数 C(2n,n) / (n+1) 。
● 暴力枚举,超时。回溯法添加字符,添加够了以后进行检查,时间复杂度 O(22n)。
1 class Solution 2 { 3 public: 4 vector<string> output; 5 6 inline bool valid(string input) 7 { 8 int i, count; 9 for (i = count = 0; i < input.size(); i++) 10 { 11 (input[i] == '(') ? count++ : count--; 12 if (count < 0) 13 return false; 14 } 15 return (count == 0); 16 } 17 void generate(string current, int pos, int length) 18 { 19 if (pos == length) 20 { 21 if (valid(current)) 22 output.push_back(current); 23 } 24 else 25 { 26 current[pos] = '('; 27 generate(current, pos + 1, length); 28 current[pos] = ')'; 29 generate(current, pos + 1, length); 30 } 31 } 32 vector<string> generateParenthesis(int n) 33 { 34 string current(2 * n, '