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

parentheses - 22. Generate Parentheses

作者头像
ppxai
发布2020-09-23 17:16:42
3100
发布2020-09-23 17:16:42
举报
文章被收录于专栏:皮皮星球

22. Generate Parentheses

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:

[ "((()))", "(()())", "(())()", "()(())", "()()()" ]

思路:

题目意思是给一个整形数字,返回合法左右括号这种组合的所有组合,典型的使用回溯法来做。

代码:

java:

代码语言:javascript
复制
class Solution {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        backtrack(res, "", 0, 0, n);
        return res;
    }
    
    private void backtrack(List<String> res, String s, int left, int right, int max) {
        if (s.length() == max *2) {
            res.add(s);
            return;
        }
        
        if (left < max) {
            backtrack(res, s + "(", left + 1, right, max);
        }
        
        if (right < left) {
            backtrack(res, s + ")", left, right + 1, max);
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019年07月22日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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