Leetcode 22. Generate Parentheses 笔记

161 阅读1分钟

Medium

思路

  • 以‘(’为开始,以二叉树的形式去探索所有情况,分别记录左右括号剩余的个数,如果哪个数量为0,将停止继续探索该位置的子树。
  • DFS
  • 注意: 结果的表示可以用新建string或者StringBuilder实现,但是!用SB的时候因为是一直在append同一个数组,所以当回溯的时候要做删除最后一位
  • sb.deleteCharAt(sb.length() - 1);

DFS过程

  • base case(一定是出口,所以被迫停止的情况不能算): 当左右都为0,更新结果,向上返回
  • 因为第一步的时候我们永远要先放一个(, 所以当left走完,回溯时判断right时要加一个条件就是,left一定要小于right,不然会导致)(

代码

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if(n <= 0) return res;
        dfs("", res, n, n);
        return res;
    }
    
    private void dfs(String s, List<String> res, int l, int r){
        if(l == 0 && r == 0){
            res.add(s);
            return;
        }
        
        if(l > 0)
            dfs(s + "(", res, l - 1, r);
        if(r > 0 && l < r)
            dfs(s + ")", res, l, r - 1);
    }
}