leetcode算法练习【22】括号生成

所有题目源代码:Git地址

题目

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

 

示例:

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

方案:根据题意判断,应当是用DFS做

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

        private void dfs(int left, int right, String s) {

            if (left==0&&right==0){
                res.add(s);
            }
            else {
                if (left>0){
                    dfs(left-1,right,s+"(");
                }if (right>left){
                    dfs(left,right-1,s+")");
                }
            }
        }
    }

复杂度计算
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)
发布了135 篇原创文章 · 获赞 187 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/symuamua/article/details/105650398