前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[算法] - 括号生成

[算法] - 括号生成

作者头像
夹胡碰
发布2021-03-24 13:22:18
4940
发布2021-03-24 13:22:18
举报
文章被收录于专栏:程序猿~

1. 描述

给出n对括号,请编写一个函数来生成所有的由n对括号组成的合法组合。 例如,给出n=3,解集为: "((()))", "(()())", "(())()", "()()()", "()(())",

出自牛客网: NC26 括号生成

2. 题解

代码语言:javascript
复制
package com.jfp;

import java.util.*;


public class Solution {
    /**
     *
     * @param n int整型
     * @return string字符串ArrayList
     */
    private ArrayList<String> res;
    public ArrayList<String> generateParenthesis (int n) {
        res = new ArrayList<>();
        recursion(n, n, "");
        return res;
    }

    private void recursion(int left, int right, String s) {
        if(left == 0 && right == 0){
            res.add(s);
        }else{
            if(left > 0){
                recursion(left - 1, right, s + "(");
            }

            if(right > left){
                recursion(left, right - 1, s + ")");
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ArrayList<String> strings = solution.generateParenthesis(2);
        System.out.println(strings);
    }
}

3. 输出结果

代码语言:javascript
复制
[(()), ()()]
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 描述
  • 2. 题解
  • 3. 输出结果
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档