论坛首页 入门技术论坛

[LeetCode] Generate Parentheses

浏览 1388 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-15  

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> res;
        char *str = new char[(2*n)+1];
        str[2*n] = '\0';
        generate(res, str, 0, 0, 2*n);
        return res;
    }
    
    void generate(vector<string>& res, char *str, int left, int cur, int n) {
        if (left == 0 && cur == n) {
            res.push_back(str);
            return ;
        }
        if (left == 0) {
            str[cur] = '(';
            generate(res, str, 1, cur+1,n);
        } else {
            if (left + cur < n) {
                str[cur] = '(';
                generate(res, str, left+1, cur+1, n);           
            }
            str[cur] = ')';
            generate(res, str, left-1, cur+1,n);
        }
    }
};

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics