leetcode 22 括号的生成

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

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

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

示例 2:

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

链接:https://leetcode-cn.com/problems/generate-parentheses
1 <= n <= 8

class Solution {
    List<String> ans= new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        compute("",n,n);
        return ans;
    }
    public void compute(String temp,int left,int right ){
          if(left==0&&right==0)
          {
              ans.add(temp);
              return;
          }
          if(left>right)
          {
              return;
          }
          if(left>0)
          {
              compute(temp+"(",left-1,right);

          }
          if(right>0)
          {
              compute(temp+")",left,right-1);
          }
    }
}
posted @ 2021-08-18 20:15  LiangLiangAA  阅读(24)  评论(0编辑  收藏  举报
theme: { name: 'geek', avatar: '', headerBackground: '' // ... },