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:

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

解题思路:

这道题显然用DFS来做。

这里需要注意的一点是:合法的括号匹配!

也就是说我们不能把右括号放到左括号前面。

在DFS是需要进行检查。

 

代码:

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ret;
        DFS(ret, "", n, n);
        return ret;
    }
private:
    void DFS(vector<string> &ret, string cur, int lNum, int rNum){
        if(lNum == 0 && rNum == 0){
            ret.push_back(cur);
            return;
        }
        if(lNum > 0)
            DFS(ret, cur+"(", lNum-1, rNum);
        
        if(lNum < rNum && rNum > 0){
            DFS(ret, cur+")", lNum, rNum-1);
        }
        
    }
};

 

posted @ 2018-06-23 05:04  妖域大都督  阅读(92)  评论(0编辑  收藏  举报