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

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

    这道题是典型的回溯法的应用,使用递归写代码并不难,但是关键还是需要理解流程,回溯法是指数的复杂度,因此测试用例中的数字应该不会太大

    类似的题目有Valid ParenthesesLongest Valid Parentheses

     1 class Solution {
     2 public:
     3     //left 和 right 分别表示可以用来放置的左括号和右括号
     4     vector<string> generateParenthesis(int n) {
     5         vector<string> res;
     6         generateParenthesis(n, n, "", res);
     7         return res;
     8     }
     9     void generateParenthesis(int left, int right, string out, vector<string> &res)
    10     {
    11         if (left > right)
    12             return;
    13         if (left == 0 && right == 0)
    14             res.push_back(out);
    15         else
    16         {
    17             if (left > 0)
    18                 generateParenthesis(left - 1, right, out + "(", res);
    19             if (right > 0)  //注意这里的if 不可以换成else与上一个if搭配,因为这里并不是非此即彼的关系
    20                 generateParenthesis(left, right - 1, out + ")", res);
    21         }
    22             
    23     }
    24 };
  • 相关阅读:
    伍佰《突然的自我》
    .NET常见ORM框架
    并发和压测工具
    底层源码调试工具
    c 冒泡排序
    c 指定范围的质数
    c 筛法列举质数
    c 牛顿法求方程近似解
    c 二分法求方程近似解
    css选择器 及其权重
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/9880084.html
Copyright © 2011-2022 走看看