LeetCode 022 Generate Parentheses

题目描述: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 {

private:

    vector<string> ret;

public:

    void solve(int dep, int maxDep, int leftNum, int leftNumTotal, string s)

    {

        //如果(个数超出,return

        if (leftNumTotal * 2 > maxDep)

            return;

            

        //如果长度足够,return    

        if (dep == maxDep){

            ret.push_back(s);

            return;

        }

        

        for(int i = 0; i < 2; i++)

        

            //加 (

            if (i == 0)

                solve(dep + 1, maxDep, leftNum + 1, leftNumTotal + 1, s + '(');

            //加 )

            else if (leftNum > 0)

                solve(dep + 1, maxDep, leftNum - 1, leftNumTotal, s + ')');

    }

    

    vector<string> generateParenthesis(int n){

        ret.clear();

        solve(0, 2 * n, 0, 0, "");

        return ret;

    }

};

 

你可能感兴趣的:(LeetCode)