前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 22. Generate Parentheses分析代码

LeetCode 22. Generate Parentheses分析代码

作者头像
desperate633
发布2018-08-22 15:55:11
2580
发布2018-08-22 15:55:11
举报
文章被收录于专栏:desperate633desperate633

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:

image.png 给定 n 对括号,请写一个函数以将其生成新的括号组合,并返回所有组合结果。

分析

深度优先搜索,关键是找限制条件,右括号的数量不能比左括号数量多。

代码

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if(n <= 0)
            return res;
        String parent = "";
        dfs(res, "",n , n);
        return res;
    }
    
    private void dfs(List<String> res, String parent, int left, int right) {
        
        if(left == 0 && right == 0) {
            res.add(parent);
            return;
        }
        
        if(left > 0) {
            dfs(res, parent+"(",left-1,right);
        }
        if(right > 0 && right > left) {
            dfs(res, parent + ")",left,right-1);
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.06.05 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档