【算法设计与分析作业题】第十二周:22. Generate Parentheses

题目

C++ solution

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        if (n == 0) {
           result.push_back("");
        } else {
            for (int i = 0; i < n; ++i) {
               vector<string> left = generateParenthesis(i);
               vector<string> right = generateParenthesis(n - 1 - i);
               for (int j = 0; j < left.size(); ++j)
               {
                  for (int k = 0; k < right.size(); ++k)
                  {
                     string str = "(" + left[j] + ")" + right[k];
                     result.push_back(str);
                  }
               }
            }
        }
        return result;
    }
};

简要题解

每个良构的 k 对括号字符串结构可以分解为:"(left)right",其中 left 和 right 也良构的括号字符串或空串,且它们包含的括号总对数为 k-1。题中求 n 对括号组成的良构的字符串,可通过上述分解方法递归求解。

猜你喜欢

转载自blog.csdn.net/For_course/article/details/84800521