• [LeetCode] 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,backtrace

    class Solution {
            vector<string> m_strs;
        public:
            void backtrace(string  str, int leftPaNum, int paNum)
            {   
                if(leftPaNum == paNum && str.size() == 2*paNum)
                {   
                    m_strs.push_back(str);
                    return;
                }   
                if(leftPaNum == paNum)
                {   
                    str += ")";
                    backtrace(str, leftPaNum, paNum);
                }   
                else
                {   
                    // left num == right num
                    if(leftPaNum  == (str.size()-leftPaNum) )
                    {   
                        str += "(";
                        backtrace(str, leftPaNum + 1, paNum);
                    }   
                    else// left num > right num
                    {   
                        str += "(";
                        backtrace(str, leftPaNum + 1, paNum);
                        str.erase(str.end() - 1); 
                        str += ")";
                        backtrace(str, leftPaNum, paNum);
                    }   
                }   
            }   
    
            vector<string> generateParenthesis(int n)
            {
                m_strs.clear();
                string str;
                backtrace(str, 0, n);
                return m_strs;
            }
    };
  • 相关阅读:
    C++实现base64编解码
    使用matplotlib绘制3D函数图像
    C++分治策略实现快速排序
    C++分治策略实现二分搜索
    C++生成随机数
    eBay 表结构
    mysql 流程函数
    无限极分类
    PHP 导出 Excell
    js
  • 原文地址:https://www.cnblogs.com/diegodu/p/4278713.html
Copyright © 2020-2023  润新知