LeetCode 22 Generate Parentheses (DFS 构造)

本文介绍了一个使用深度优先搜索(DFS)生成所有有效括号组合的算法。对于输入的整数n,该算法能够生成所有可能的有效括号组合,确保左括号的数量始终不少于右括号且不超过n。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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即可,DFS构造

public class Solution {

    public void DFS(int l, int r, int n, String str, List<String> ans) {
        if (l == n && r == n) {
            ans.add(str);
            return;
        }
        if (l > r) {
            DFS(l, r + 1, n, str + ")", ans);
        }
        if (l < n) {
            DFS(l + 1, r, n, str + "(", ans);
        }
    }
    
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        DFS(0, 0, n, "", ans);
        return ans;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值