[LeetCode] Generate Parentheses

简介: Well, there are two ways to add a open or close parenthesis to the current string. If number of ( is less than n, you can add (; If number of ) is less than number of (, you can add ).

Well, there are two ways to add a open or close parenthesis to the current string.

  1. If number of ( is less than n, you can add (;
  2. If number of ) is less than number of (, you can add ).

Maintain a res for all the possible parenthesis and a temporary string sol for the current answer. Now we have the following code.

 1 class Solution {
 2 public:
 3     vector<string> generateParenthesis(int n) {
 4         vector<string> res;
 5         string sol;
 6         genParen(sol, 0, 0, n, res);
 7         return res;
 8     }
 9 private:
10     void genParen(string& sol, int open, int close, int total, vector<string>& res) {
11         if (open == total && close == total) {
12             res.push_back(sol);
13             return;
14         }
15         if (open < total) {
16             sol += '(';
17             genParen(sol, open + 1, close, total, res);
18             sol.resize(sol.length() - 1);
19         }
20         if (close < open) {
21             sol += ')';
22             genParen(sol, open, close + 1, total, res);
23             sol.resize(sol.length() - 1);
24         }
25     }
26 }; 

 

目录
相关文章
LeetCode 301. Remove Invalid Parentheses
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。 说明: 输入可能包含了除 ( 和 ) 以外的字符。
50 0
LeetCode 301. Remove Invalid Parentheses
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
55 0
LeetCode 241. Different Ways to Add Parentheses
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
90 0
Leetcode-Easy 20. Valid Parentheses
LeetCode 20:有效的括号 Valid Parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 有效字符串需满足: 左括号必须用相同类型的右括号闭合。
741 0
|
Java
[LeetCode] Valid Parentheses 验证括号是否有效闭合
链接:https://leetcode.com/problems/valid-parentheses/#/description难度:Easy题目:20.
983 0
LeetCode - 32. Longest Valid Parentheses
32. Longest Valid Parentheses  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个由'('和')'组成的字符串,求最长连续匹配子串长度.
948 0
LeetCode - 20. Valid Parentheses
20. Valid Parentheses  Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个括号序列,检查括号是否按顺序匹配.
851 0
LeetCode - 22. Generate Parentheses
22. Generate Parentheses Problem's Link  ---------------------------------------------------------------------------- Mean:  给定一个数n,输出由2*n个'('和')'组成的字符串,该字符串符合括号匹配规则.
840 0