zoukankan      html  css  js  c++  java
  • 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:

    "((()))", "(()())", "(())()", "()(())", "()()()"

     1 #include <vector>
     2 #include <string>
     3 using namespace std;
     4 class Solution {
     5 public:
     6     vector<string> generateParenthesis(int n) {
     7         vector<string> result;
     8         vector<bool> path;
     9         dfs(0,0,0,path,result,n);
    10         return result;   
    11     }
    12 
    13 private:
    14     void dfs(int curr,int r,int l,vector<bool>& path,
    15         vector<string>& result,int n){
    16         if(curr == 2*n){
    17             string s;
    18             for(int i=0;i<2*n;i++){
    19                 if(path[i]==true){
    20                     s.push_back('(');
    21                 }else s.push_back(')');
    22             }
    23             result.push_back(s);
    24             return;
    25         }
    26         
    27         if(r==l){
    28             path.push_back(true);
    29             dfs(curr+1,r+1,l,path,result,n);
    30             path.pop_back();
    31         }else if(r>l && r<n){
    32             path.push_back(true);
    33             dfs(curr+1, r+1, l, path, result, n);
    34             path.pop_back();
    35             path.push_back(false);
    36             dfs(curr+1, r, l+1, path, result, n);
    37             path.pop_back();
    38         }else{
    39             path.push_back(false);
    40             dfs(curr+1,r,l+1,path,result,n);
    41             path.pop_back();
    42         }
    43         
    44     }
    45 };
    46 
    47 int main()
    48 {
    49     Solution s;
    50     vector<string> result;
    51     result = s.generateParenthesis(3);
    52     return 0;
    53 }
  • 相关阅读:
    在WIN10下搭建Robot Framework环境
    Robot Framework导入selenium2library库不成功的解决方法
    git命令大全
    Axure RP 8过期,用户名和序列号(注册码)
    MySQL用命令行快速导出数据备份
    JMeter—正则表达式提取器
    用JMeter进行接口测试
    d3-project
    bower 问题
    andriod studio
  • 原文地址:https://www.cnblogs.com/wxquare/p/5003432.html
Copyright © 2011-2022 走看看