Leetcode | Parentheses 相关

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就可以添加左括号。只要右括号数大于左括号数就可以添加右括号。


 1 class Solution {
2 public:
3 vector<string> generateParenthesis(int n) {
4 vector<string> res;
5
6 recursive(n, n, "", res);
7
8 return res;
9 }
10
11 void recursive(int n1, int n2, string str, vector<string> &res) {
12 if (n1 == 0 && n2 == 0) {
13 res.push_back(str);
14 return;
15 }
16
17 if (n1 >= 1) {
18 recursive(n1 - 1, n2, str + "(", res);
19 }
20
21 if (n2 > n1) {
22 recursive(n1, n2 - 1, str + ")", res);
23 }
24 }
25 };

网上查了一下,竟然还和Catalan数有关。

通项公式是: \(\frac{(2n)!}{(n+1)!n!}\)

递推公式是 \(C_0=1\ and\ C_{n+1}=\sum\limits^n_{i=0}{C_{i}C_{n-i}}\)

n个+1和n个-1构成2n项\(a_1,a_2,\ldots,a_n\),其部分和满足\(a_1+a_2+\ldots+a_k\ge{}0,0\le{}k\le{}2n\)的序列个数等于第n个Catalan数\(C_n\)。

Valid Parentheses

Given a string containing just the characters ‘(‘, ‘)‘, ‘{‘, ‘}‘, ‘[‘ and
‘]‘, determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid
but "(]" and "([)]" are not.

用了一个栈去实现。当前哪果是右括号,那么栈顶必须是对应的左括号才行。栈为空的话,也只能push左括号。


 1 class Solution {
2 public:
3 bool isValid(string s) {
4 if (s.empty()) return true;
5
6 stack<char> st;
7
8 for (int i = 0; i < s.length(); ++i) {
9 if (st.empty()) {
10 if (s[i] == ‘(‘ || s[i] == ‘[‘ || s[i] == ‘{‘) st.push(s[i]);
11 else return false;
12 } else if (s[i] == ‘(‘ || s[i] == ‘[‘ || s[i] == ‘{‘) {
13 st.push(s[i]);
14 } else if (s[i] == ‘)‘) {
15 if (st.top() == ‘(‘) st.pop();
16 else return false;
17 } else if (s[i] == ‘]‘) {
18 if (st.top() == ‘[‘) st.pop();
19 else return false;
20 } else if (s[i] == ‘}‘) {
21 if (st.top() == ‘{‘) st.pop();
22 else return false;
23 } else {
24 return false;
25 }
26 }
27 return st.empty();
28 }
29 };

重构一下:


 1 class Solution {
2 public:
3 bool isValid(string s) {
4 if (s.empty()) return true;
5
6 stack<char> st;
7
8 for (int i = 0; i < s.length(); ++i) {
9 if (s[i] == ‘(‘ || s[i] == ‘[‘ || s[i] == ‘{‘) {
10 st.push(s[i]);
11 continue;
12 } if (st.empty()) {
13 return false;
14 }
15
16 if (s[i] == ‘)‘ && st.top() != ‘(‘) return false;
17 if (s[i] == ‘]‘ && st.top() != ‘[‘) return false;
18 if (s[i] == ‘}‘ && st.top() != ‘{‘) return false;
19 st.pop();
20 }
21 return st.empty();
22 }
23 };

用map再重构,可以再简洁一些。


 1 class Solution {
2 public:
3 bool isValid(string s) {
4 if (s.empty()) return true;
5
6 map<char, char> pars;
7 pars[‘)‘] = ‘(‘;
8 pars[‘]‘] = ‘[‘;
9 pars[‘}‘] = ‘{‘;
10
11 stack<char> st;
12
13 for (int i = 0; i < s.length(); ++i) {
14 if (pars.find(s[i]) == pars.end()) {
15 st.push(s[i]);
16 continue;
17 } if (st.empty()) {
18 return false;
19 }
20
21 if (st.top() != pars[s[i]]) return false;
22 st.pop();
23 }
24 return st.empty();
25 }
26 };

时间: 2024-08-25 05:55:37

Leetcode | Parentheses 相关的相关文章

leetcode sum相关算法题

1. Two Sum(https://oj.leetcode.com/problems/two-sum/) 解题思路: 解法一: 暴力,O(n2)时间复杂度,TLE 解法二:利用hash, 记录下数组中每个值对应的下标,再遍历一遍数组,通过查看target-num[i]的值是否在map中来确定另一个数值.时间复杂度O(n) 解法三:对num数组排序,O(nlog(n)), 然后左右夹逼O(n). 但这道题要求记录下标,故这个方法行不通. python代码如下: 1 def twoSum(self

leetcode -- 旋转矩阵相关问题

给定一个 n × n 的二维矩阵表示一个图像. 将图像顺时针旋转 90 度. 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵.请不要使用另一个矩阵来旋转图像. 示例 1: 给定 matrix = [ [1,2,3], [4,5,6], [7,8,9] ], 原地旋转输入矩阵,使其变为: [ [7,4,1], [8,5,2], [9,6,3] ] 解题思路:先写出其转置矩阵,然后每行列表反转 1 class Solution: 2 def rotate(self, matrix

Leetcode回溯相关题目Python实现

1.46题,全排列 https://leetcode-cn.com/problems/permutations/ class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ n = len(nums) results = [] def backtrack(first = 0): if first ==

leetcode 之 Longest Valid Parentheses

leetcode中和括号匹配相关的问题共有三个,分别是: Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are a

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

LeetCode:Valid Parentheses - 合理的括号搭配

1.题目名称 Valid Parentheses(合理的括号搭配) 2.题目地址 https://leetcode.com/problems/valid-parentheses/ 3.题目内容 英文:Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the

【LeetCode】22. Generate Parentheses (I thought I know Python...)

I thought I know Python... Actually , I know nothing... 这个题真想让人背下来啊,每一句都很帅!!! 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: [ "((()))", "

leetcode Remove Invalid Parentheses

题目连接 https://leetcode.com/problems/remove-invalid-parentheses/ Remove Invalid Parentheses Description Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may co

[LeetCode][JavaScript]Remove Invalid Parentheses

Remove Invalid Parentheses Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results. Note: The input string may contain letters other than the parentheses ( and ). Examples: "()())()"