美文网首页
leetcode 22 - 括号生成

leetcode 22 - 括号生成

作者: 那钱有着落吗 | 来源:发表于2021-08-27 10:19 被阅读0次

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses

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

有效括号组合需满足:左括号必须以正确的顺序闭合。

 

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:

输入:n = 1
输出:["()"]
 

提示:

1 <= n <= 8

思路

首先要好好审题,符合条件的括号序列必然是左边与右边的括号是相等的,所以剩余左括号总数要小于等于右括号。 递归把所有符合要求的加上去就行了,那么就按照这个思路编码即可。

题解:

class Solution {
        List<String> res = new ArrayList<>();
        public List<String> generateParenthesis(int n) {
            if(n <= 0){
                return res;
            }
            getParenthesis("",n,n);
            return res;
        }

        private void getParenthesis(String str,int left, int right) {
            if(left == 0 && right == 0 ){
                res.add(str);
                return;
            }
            if(left == right){
                //剩余左右括号数相等,下一个只能用左括号
                getParenthesis(str+"(",left-1,right);
            }else if(left < right){
                //剩余左括号小于右括号,下一个可以用左括号也可以用右括号
                if(left > 0){
                    getParenthesis(str+"(",left-1,right);
                }
                getParenthesis(str+")",left,right-1);
            }
        }
    }

在上述的答案中,最核心的地方就在于:

 if(left > 0){
      getParenthesis(str+"(",left-1,right);
 }
 getParenthesis(str+")",left,right-1);

其实正如作者写的注释,这里剩余左括号小于右括号,下一个可以用左括号也可以用右括号,所以这里其实就是一种写法,让程序可以走两种逻辑,如果还是不理解,那么这段程序我也可以这么写:

 if(left > 0){
      getParenthesis(str+"(",left-1,right);
 }
 if(right > 0){
   getParenthesis(str+")",left,right-1);
 }

理解了吧,其实就是控制住让left不会小于0,right不小于0,回溯出所有的括号序列。

相关文章

  • 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/dltmiltx.html