2017-09-11 LeetCode_022 Generate Parentheses

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

solution:

class Solution {
2
public:
3
    void deep(vector<string> & ans, int n, int step, int use, string str) {
4
        if (step == 2*n) {
5
            if (use == 0) ans.push_back(str);
6
            return;
7
        }
8
        if (use > 0) deep(ans, n, step+1, use-1, str+')');
9
        if (use < n) deep(ans, n, step+1, use+1, str+'(');
10
    }
11
    vector<string> generateParenthesis(int n) {
12
        vector<string> ans;
13
        deep(ans, n, 0, 0, "");
14
        return ans;
15
    }
16
};





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章