力扣括号匹配:-【力扣Leetcode题解系列之0022—Generate Parentheses 括号生成】 - 在回溯过程中,每个合法组合的生成需要 (O(2n)) 的时间来构建字符串
22. Generate Parentheses 括号生成:多语言实现与分析
一、题目分析
给定整数 n,要求生成所有由 n 对括号组成的合法括号组合。合法的括号组合意味着每个左括号都有与之匹配的右括号,且括号的嵌套顺序正确。
二、常用解法
回溯法
思路:
回溯法本质上是一种深度优先搜索(DFS)策略,通过递归尝试所有可能的组合,并在不满足条件时进行剪枝,避免无效搜索。对于括号生成问题,我们从一个空字符串开始,逐步添加左括号 ( 和右括号 )。两个关键条件用于决定是否继续添加括号:
左括号的数量不能超过 n。只要左括号数量未达到 n,就可以继续添加左括号。右括号的数量不能超过左括号的数量。只有当右括号数量小于左括号数量时,才能添加右括号。
当左括号和右括号的数量都达到 n 时,说明得到了一个合法的括号组合,将其加入结果集。
优点:回溯法能够系统地遍历所有可能的情况,确保不会遗漏任何合法的括号组合。它的实现相对直观,通过递归结构可以清晰地表达问题的求解过程。
三、多语言实现
Python实现
class Solution:
def generateParenthesis(self, n):
res = []
self.dfs(res, n, n, '')
return res
def dfs(self, res, left, right, path):
if left == 0 and right == 0:
res.append(path)
return
if left > 0:
self.dfs(res, left - 1, right, path + '(')
if left < right:
self.dfs(res, left, right - 1, path + ')')
Java实现
import java.util.ArrayList;
import java.util.List;
class Solution {
public ListgenerateParenthesis(int n) {
Listres = new ArrayList<>();
dfs(res, "", n, 0, 0);
return res;
}
private void dfs(Listres, String path, int n, int leftCount, int rightCount) { 拼多多帮助力入口
if (rightCount > leftCount || leftCount > n || rightCount > n) {
return;
}
if (leftCount == rightCount && leftCount == n) {
res.add(path);
return;
}
dfs(res, path + "(", n, leftCount + 1, rightCount);
dfs(res, path + ")", n, leftCount, rightCount + 1);
}
}
C++实现
#include
#include
using namespace std;
class Solution {
public:
vectorgenerateParenthesis(int n) {
vectorres;
int lc = 0, rc = 0;
dfs(res, "", n, lc, rc);
return res;
}
void dfs(vector& res, string path, int n, int lc, int rc) {
if (rc > lc || lc > n || rc > n) return;
if (lc == rc && lc == n) {
res.push_back(path);
return;
}
dfs(res, path + '(', n, lc + 1, rc);
dfs(res, path + ')', n, lc, rc + 1);
}
};
Go实现
package main
import "fmt"
func generateParenthesis(n int) []string {
var res []string
dfs(&res, "", n, 0, 0)
return res
}
func dfs(res *[]string, path string, n, leftCount, rightCount int) {
if rightCount > leftCount || leftCount > n || rightCount > n {
return
}
if leftCount == rightCount && leftCount == n {
*res = append(*res, path)
return
}
dfs(res, path+"(", n, leftCount+1, rightCount)
dfs(res, path+")", n, leftCount, rightCount+1)
}
四、算法复杂性分析
时间复杂度
生成的合法括号组合数量为卡特兰数 (C_{2n}^n / (n + 1)),约为 (\frac{4^n}{n\sqrt{n}})。在回溯过程中,每个合法组合的生成需要 (O(2n)) 的时间来构建字符串。因此,总的时间复杂度为 (O(\frac{4^n}{\sqrt{n}}))。
空间复杂度
空间复杂度主要取决于递归调用栈的深度和存储结果的空间。递归调用栈的最大深度为 (2n),存储结果的空间为生成的合法括号组合数量,即 (O(\frac{4^n}{\sqrt{n}}))。因此,总的空间复杂度为 (O(\frac{4^n}{\sqrt{n}}))。
五、实现的关键点和难度
关键点
递归与剪枝条件:准确理解和实现递归过程中的剪枝条件是关键。左括号数量不超过 n 以及右括号数量不超过左括号数量这两个条件决定了搜索空间的边界,确保只生成合法的括号组合。状态跟踪:在递归过程中,需要准确跟踪当前已经使用的左括号和右括号的数量,以及当前生成的括号字符串。这些状态信息用于决定下一步是否继续添加左括号或右括号。结果收集:当满足左括号和右括号数量都为 n 时,要将生成的合法括号字符串正确地收集到结果集中。
难度
递归逻辑理解:回溯法基于递归实现,对于不熟悉递归思想的人来说,理解递归调用的过程和状态变化可能有一定难度。特别是在处理多个状态变量(如左括号数量、右括号数量)时,需要清晰地把握它们在递归过程中的变化情况。剪枝条件设计:设计合理的剪枝条件需要对问题有深入的理解。如果剪枝条件过于宽松,可能会导致无效搜索,增加时间复杂度;如果剪枝条件过于严格,可能会遗漏一些合法的括号组合。
六、扩展及难度加深题目
扩展题目1:生成多种类型括号的组合
题目描述:除了圆括号 (),增加方括号 [] 和花括号 {},给定每种括号的对数,要求生成所有合法的括号组合。解题思路:在原回溯法的基础上,扩展剪枝条件和递归逻辑。对于每种类型的括号,分别跟踪其已使用的数量。添加括号时,需要满足每种括号的左括号数量不超过给定的对数,并且右括号数量不超过左括号数量。代码示例(以Python为例)
class Solution:
def generateMultiTypeParenthesis(self, n1, n2, n3):
res = []
self.dfs(res, "", n1, n2, n3, 0, 0, 0)
return res
def dfs(self, res, path, n1, n2, n3, l1, l2, l3):
if l1 == n1 and l2 == n2 and l3 == n3:
res.append(path)
return
if l1 < n1:
self.dfs(res, path + '(', n1, n2, n3, l1 + 1, l2, l3)
if l1 > 0:
self.dfs(res, path + ')', n1, n2, n3, l1, l2, l3)
if l2 < n2:
self.dfs(res, path + '[', n1, n2, n3, l1, l2 + 1, l3)
if l2 > 0:
self.dfs(res, path + ']', n1, n2, n3, l1, l2, l3)
if l3 < n3:
self.dfs(res, path + '{', n1, n2, n3, l1, l2, l3 + 1)
if l3 > 0:
self.dfs(res, path + '}', n1, n2, n3, l1, l2, l3)
扩展题目2:生成带权重的括号组合
题目描述:给每种括号赋予一个权重,例如 ( 的权重为 1,[ 的权重为 2,{ 的权重为 3 等。要求生成所有合法的括号组合,并计算每个组合的权重之和,权重之和需满足一定条件(如在某个范围内)。解题思路:在回溯过程中,除了跟踪括号的使用数量和生成括号字符串外,还需要记录当前组合的权重之和。在递归调用时,根据添加的括号类型更新权重之和,并在满足权重条件时收集结果。代码示例(以Python为例)
class Solution:
def generateWeightedParenthesis(self, n1, n2, n3, minWeight, maxWeight):
res = []
self.dfs(res, "", n1, n2, n3, 0, 0, 0, 0)
return [path for path, weight in res if minWeight <= weight <= maxWeight]
def dfs(self, res, path, n1, n2, n3, l1, l2, l3, weight):
if l1 == n1 and l2 == n2 and l3 == n3:
res.append((path, weight))
return
if l1 < n1:
self.dfs(res, path + '(', n1, n2, n3, l1 + 1, l2, l3, weight + 1)
if l1 > 0:
self.dfs(res, path + ')', n1, n2, n3, l1, l2, l3, weight + 1)
if l2 < n2:
self.dfs(res, path + '[', n1, n2, n3, l1, l2 + 1, l3, weight + 2)
if l2 > 0:
self.dfs(res, path + ']', n1, n2, n3, l1, l2, l3, weight + 2)
if l3 < n3:
self.dfs(res, path + '{', n1, n2, n3, l1, l2, l3 + 1, weight + 3)
if l3 > 0:
self.dfs(res, path + '}', n1, n2, n3, l1, l2, l3, weight + 3)
难度加深题目1:生成满足特定嵌套规则的括号组合
题目描述:给定一些特定的嵌套规则,例如圆括号不能直接嵌套在花括号内,要求生成所有满足这些规则的括号组合。解题思路:在回溯过程中,除了原有的括号数量限制条件外,增加对嵌套规则的检查。每次尝试添加括号时,根据当前生成的括号字符串和嵌套规则判断是否可以添加该括号。代码示例(以Python为例)
class Solution:
def generateConstrainedParenthesis(self, n1, n2, n3):
res = []
self.dfs(res, "", n1, n2, n3, 0, 0, 0)
return res
def dfs(self, res, path, n1, n2, n3, l1, l2, l3):
if l1 == n1 and l2 == n2 and l3 == n3:
res.append(path)
return
if l1 < n1:
if not path or path[-1]!= '{':
self.dfs(res, path + '(', n1, n2, n3, l1 + 1, l2, l3)
if l1 > 0:
self.dfs(res, path + ')', n1, n2, n3, l1, l2, l3)
if l2 < n2:
self.dfs(res, path + '[', n1, n2, n3, l1, l2 + 1, l3)
if l2 > 0:
self.dfs(res, path + ']', n1, n2, n3, l1, l2, l3)
if l3 < n3:
self.dfs(res, path + '{', n1, n2, n3, l1, l2, l3 + 1)
if l3 > 0:
self.dfs(res, path + '}', n1, n2, n3, l1, l2, l3)
难度加深题目2:生成最大嵌套深度满足条件的括号组合
题目描述:给定一个最大嵌套深度 k,要求生成所有合法括号组合,且这些组合的最大嵌套深度不超过 k。解题思路:在回溯过程中,增加对当前括号组合最大嵌套深度的跟踪。每次添加括号时,更新最大嵌套深度,并根据最大嵌套深度是否超过 k 来决定是否继续递归。代码示例(以Python为例)
class Solution:
def generateBracketsWithMaxDepth(self, n, k):
res = []
self.dfs(res, "", n, 0, 0, 0)
return res
def dfs(self, res, path, n, leftCount, rightCount, depth):
if leftCount == rightCount and leftCount == n:
res.append(path)
return
if leftCount < n and depth < k:
self.dfs(res, path + '(', n, leftCount + 1, rightCount, depth + 1)
if leftCount > rightCount:
newDepth = depth - 1 if rightCount == leftCount - 1 else depth
self.dfs(res, path + ')', n, leftCount, rightCount + 1, newDepth)
七、应用场合
编译器语法分析:在编译器的语法分析阶段,需要生成所有可能的合法语法结构,括号匹配是其中的一部分。例如,在解析表达式时,需要考虑各种括号的合法组合,以确保表达式的语法正确性。组合优化问题:在一些组合优化问题中,需要生成满足特定条件的组合。例如,在资源分配问题中,不同类型的资源分配可以看作是不同类型的“括号”,通过生成所有合法的组合来寻找最优的资源分配方案。密码学与编码:在密码学和编码领域,生成满足特定规则的字符组合是常见的任务。例如,生成具有特定结构的密钥或编码字符串,括号生成的思想可以应用于生成满足特定嵌套规则或字符组合规则的字符串。游戏开发:在游戏开发中,例如生成迷宫的路径或解谜游戏中的线索组合,可能会用到类似括号生成的方法,通过生成所有可能的组合并根据游戏规则进行筛选,来创建游戏内容。,力扣括号匹配