My back tracking solution:

class Solution {
    List<String> res = new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        backTracking(n,  0 , 0, new StringBuilder(), res);
        return res;
    }
    
    private void backTracking(int n, int lCount, int rCount, StringBuilder s, List<String> res){
        if(lCount==n && rCount==n){
            res.add(s.toString());
            s = new StringBuilder();
            return;
        }
        if(lCount<n){
            s.append("(");
            backTracking(n, lCount+1, rCount, s, res);
            s.deleteCharAt(s.length()-1);
        }
        if(rCount<lCount){
            s.append(")");
            backTracking(n, lCount, rCount+1, s, res);
            s.deleteCharAt(s.length()-1);
        }
    }
}

 

posted on 2022-04-19 11:23  阳光明媚的菲越  阅读(19)  评论(0编辑  收藏  举报