leetcode 22. 括号生成【dfs】

生成字符串的过程类似于二叉树;
当前字符串添加左括号相当于添加一个左叶子节点,添加右括号相当于添加一个右叶子节点;
当左、右括号剩余数量为0时,说明字符串已经完成,

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

    public void dfs(String cur,int left,int right,List<String> res){
        if(left == 0&&right==0){
            res.add(cur);
            return;
        }
        if(left>0)
            dfs(cur+"(",left-1,right,res);
        if(right>0)
            dfs(cur+")",left,right-1,res);
    }
}
发布了55 篇原创文章 · 获赞 0 · 访问量 762

猜你喜欢

转载自blog.csdn.net/er_ving/article/details/104750438