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:

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

    解题思路:

    这个是用迭代方法,当左括号和又括号的个数相同且等于输入n时将此时的字符串存入vector中。

    这题是用回溯方法估计会更好些。

    代码:

     1 class Solution {
     2 public:
     3     vector<string> generateParenthesis(int n) {
     4         vector<string> ret;
     5         generate(n, 0, 0, "", ret);
     6         return ret;
     7     }
     8     void generate(int n, int numl, int numr, string str, vector<string>& ret) {
     9         if (numl < numr || numl > n || numr > n)
    10             return;
    11         if (numl == n && numr == n)
    12             ret.push_back(str);
    13         if (numl < n) {
    14             generate(n, numl+1, numr, str+"(", ret);
    15             generate(n, numl, numr+1, str+")", ret);
    16         } else {
    17             generate(n, numl, numr+1, str+")", ret);
    18         }
    19     }
    20 };
    View Code
  • 相关阅读:
    (判断是否为弱联通分量) poj 2762
    (最大生成树) poj 1979
    (暴力) bzoj 2208
    (BFS) bzoj 1102
    (并查集) bzoj 1161
    (数学) bzoj 1800
    (博弈) bzoj 2460
    (dinic) poj 3469
    (双端队列优化的SPFA) bzoj 2100
    (判断负环) bzoj 2019
  • 原文地址:https://www.cnblogs.com/gsz-/p/9553616.html
Copyright © 2011-2022 走看看