22 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> res;
        if ( n == 0 ) {
            res.push_back("");
            return res;
        }
        vector<string> tmp_res1, tmp_res2;
        for ( int i = 0; i <= n-1; i++) {
            tmp_res1 = generateParenthesis(n-1-i);
            tmp_res2 = generateParenthesis(i);
            for ( int i1 = 0; i1 <= tmp_res1.size()-1; i1++ ) {
                for ( int i2 = 0; i2 <= tmp_res2.size()-1; i2++ ) {
                    res.push_back("("+tmp_res1[i1]+")" + tmp_res2[i2]);
                }
            }
        }
        return res;
    }
};

Notes
Classify the valid parenthesis array as follows, and recursively solve for the parenthesis array.

"(" + parenthesis(n-1)+")"
"(" + parenthesis(n-2)+")" + parenthesis(1)
.
.
.
.
"(" + ")" + parenthesis(n-1)

Question: iterative solution?

results matching ""

    No results matching ""