zoukankan      html  css  js  c++  java
  • LeetCode

     22. Generate Parentheses

    Problem's Link

     ----------------------------------------------------------------------------

    Mean: 

    给定一个数n,输出由2*n个'('和')'组成的字符串,该字符串符合括号匹配规则.

    analyse:

    递归求解.

    Time complexity: O(N)

     

    view code

    /**
    * -----------------------------------------------------------------
    * Copyright (c) 2016 crazyacking.All rights reserved.
    * -----------------------------------------------------------------
    *       Author: crazyacking
    *       Date  : 2016-02-17-17.58
    */
    #include <queue>
    #include <cstdio>
    #include <set>
    #include <string>
    #include <stack>
    #include <cmath>
    #include <climits>
    #include <map>
    #include <cstdlib>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    typedef long long(LL);
    typedef unsigned long long(ULL);
    const double eps(1e-8);

    class Solution
    {
    public:
       vector<string> generateParenthesis(int n)
       {
           vector<string> res;
           recursive(res,"",n,0);
           return res;
       }
       void recursive(vector<string>& v,string str,int n,int m)
       {
           if(n==0 && m==0)
           {
               v.push_back(str);
               return;
           }
           if(m>0)
               recursive(v,str+")",n,m-1);
           if(n>0)
               recursive(v,str+"(",n-1,m+1);
       }
    };

    int main()
    {
       Solution solution;
       int n;
       while(cin>>n)
       {
           auto ans=solution.generateParenthesis(n);
           for(auto p:ans)
           {
               cout<<p<<endl;
           }
           cout<<"End."<<endl;
       }
       return 0;
    }
    /*

    */
  • 相关阅读:
    住建部第一批城市更新试点名单
    新城建试点城市
    日常笔记
    简单的C++配置模块
    C++ 异常 OR 错误码
    数独的暴力破解法
    MySQL语法数据库操作 Test
    Python中的staticmethod和classmethod Test
    Python中的__init__()、__new__()、__del__()方法 Test
    MySQL语法数据库表操作 Test
  • 原文地址:https://www.cnblogs.com/crazyacking/p/5196111.html
Copyright © 2011-2022 走看看