zoukankan      html  css  js  c++  java
  • 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);
            }
            
        }
    };
  • 相关阅读:
    vim 命令详解
    vim基础命令
    JSP取得绝对路径
    sigar开发(java)
    HDU-5273
    HDU-1671
    HDU-1251
    POJ-1743
    POJ-2774
    hihocoder 1145 : 幻想乡的日常
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9216206.html
Copyright © 2011-2022 走看看