首页 > 代码库 > 【Leetcode】Generate Parentheses

【Leetcode】Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

分析:此类问题一般和递归有关,仔细寻找规律发现可以通过往一个括号“()”的中间和右边(因为左边必须以左括号开始)两部分加入新的括号,可以得到结果。


class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        if(n == 0) 
        {
            result.push_back("");
            return result;
        }
        if(n == 1)
        {
            result.push_back("()");
            return result;
        }
        
        for(int i = 0; i < n; i++)
        {
            vector<string> left_temp = generateParenthesis(i);
            for(auto left = left_temp.begin(); left != left_temp.end(); left++)
            {
                vector<string> right_temp = generateParenthesis(n - i - 1); 
                for(auto right = right_temp.begin(); right != right_temp.end(); right++)
                    result.push_back("(" + *left + ")" + *right);
            }
            
        }
        
        return result;
            
    }
};