LeetCode22 括号生成

题目

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
有效括号组合需满足:左括号必须以正确的顺序闭合。

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

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

提示:
1 <= n <= 8

方法

方法1:回溯法

  • 时间复杂度:O()
  • 空间复杂度:O()
class Solution {
    private List<String> result = new ArrayList<>();
    private StringBuffer temp = new StringBuffer();
    public List<String> generateParenthesis(int n) {
        if(n<1){
            return result;
        }
        dfs(n,0,0,0);
        return result;
    }
    private void dfs(int n,int depth,int open,int close){
        if(depth==n*2){
            result.add(temp.toString());
            return;
        }
        if(open<n){
            temp.append("(");
            dfs(n,depth+1,open+1,close);
            temp.deleteCharAt(temp.length()-1);
        }
        if(close<open){
            temp.append(")");
            dfs(n,depth+1,open,close+1);
            temp.deleteCharAt(temp.length()-1);
        }
    }
}

方法2:

posted @ 2021-10-05 21:12  你也要来一颗长颈鹿吗  阅读(24)  评论(0)    收藏  举报