美文网首页
Leetcode 22 括号生成

Leetcode 22 括号生成

作者: hekirakuno | 来源:发表于2019-11-01 15:00 被阅读0次

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

思路:回溯法(参考学长大神的解做的)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<String>();
        if(n<1){
            return ans;
        }
        //初始状态
        //最终结果集,当前串,已有左括号数,右括号数,要求的括号对
        ans = returnSearch(ans,"",0,0, n);
        return ans;
    }
    public List<String> returnSearch(List<String> ans,String temp,int left,int right,int n){
        if(left>n||right>left){
            return ans;
        }
        if(left==right&&left==n){
            ans.add(temp);
        }
        ans = returnSearch(ans,temp + "(",left+1,right,n);
        ans = returnSearch(ans,temp + ")",left,right+1,n);
        return ans;
    }
}

相关文章

  • a 递归

    1 括号生成(leetcode 22)

  • LeetCode-22. 括号生成

    参考:第7课-泛型递归、树的递归 LeetCode-22. 括号生成 22. 括号生成 数字 n 代表生成括号的对...

  • LeetCode 22. 括号生成

    1、题目 22. 括号生成 - 力扣(LeetCode) https://leetcode-cn.com/prob...

  • 22. 括号生成

    22. 括号生成[https://leetcode.cn/problems/generate-parenthese...

  • LeetCode-22-括号生成

    LeetCode-22-括号生成 题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且...

  • LeetCode:22. 括号生成

    问题链接 22. 括号生成[https://leetcode.cn/problems/generate-paren...

  • 22. 括号生成

    22. 括号生成 题目链接:https://leetcode-cn.com/problems/generate-p...

  • Leetcode 22 括号生成

    题目 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 n ...

  • [LeetCode]22、括号生成

    题目描述 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。 例如,给出 ...

  • Leetcode 22 括号生成

    给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。例如,给出 n = 3,...

网友评论

      本文标题:Leetcode 22 括号生成

      本文链接:https://www.haomeiwen.com/subject/ptnfbctx.html