Java算法_括号生成(LeetCode_Hot100)

题目描述: 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

获得更多?
算法思路,案例演示,代码文档,算法解析的私得

算法思想: 使用了递归回溯的思想来生成有效的括号组合

在这里插入图片描述

项目源码

/**
 * 2 * @Author: LJJ
 * 3 * @Date: 2023/7/19 9:30
 * 4
 */
import java.util.ArrayList;
import java.util.List;

public class GenerateParentheses {

    public static List<String> generateParentheses(int n) {
        List<String> result = new ArrayList<>();
        backtrack(result, "", 0, 0, n);
        return result;
    }

    private static void backtrack(List<String> result, String current, int open, int close, int n) {
        // 终止条件:当当前括号组合的长度达到 2n 时,添加到结果集中
        if (current.length() == 2 * n) {
            result.add(current);
            return;
        }

        // 如果左括号数量小于 n,则可以继续添加左括号
        if (open < n) {
            backtrack(result, current + "(", open + 1, close, n);
        }
        // 如果右括号数量小于左括号数量,则可以继续添加右括号
        if (close < open) {
            backtrack(result, current + ")", open, close + 1, n);
        }
    }

    public static void main(String[] args) {
        int n = 3;
        List<String> parentheses = generateParentheses(n);
        System.out.println("Valid Parentheses Combinations for n=" + n + ":");
        for (String combination : parentheses) {
            System.out.println(combination);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值