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

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

    解题思路:

    基本想法是用递归,当左括号数 < n, 可以继续放左括号,当右括号数<左括号数时,可以继续放右括号。 

     1 class Solution {
     2 public:
     3     vector<string> generateParenthesis(int n) {
     4         vector<string> result;
     5         if (n > 0) {
     6             generateParenthesis(n, "", 0, 0, result);
     7         }
     8         
     9         return result;
    10     }
    11 private:
    12     void generateParenthesis(int n, string s, int l, int r, vector<string> &result) {
    13         if (l == n) {
    14             result.push_back(s.append(n - r, ')'));
    15             return;
    16         }
    17         generateParenthesis(n, s + '(', l + 1, r, result);
    18         
    19         if (r < l) {
    20            generateParenthesis(n, s + ')', l, r + 1, result); 
    21         }
    22     }
    23 };
  • 相关阅读:
    【Linux】没有网的情况下如何安装GCC
    【PL/SQL】PLSQL Developer注册码
    【JS】字符串操作
    【java】svn显示&#215;
    线段树
    病毒感染者
    并查集
    最小的N个和(堆)
    priority_queue的用法
    打印杨辉三角
  • 原文地址:https://www.cnblogs.com/skycore/p/5256156.html
Copyright © 2011-2022 走看看