Concise Java backtracking solution


  • 0
    D
    public List<String> generateParenthesis(int n) {
        List<String> ret = new LinkedList<>();
        backtrack("", ret, n, n);
        return ret;
    }
    
    void backtrack(String str, List<String> ret, int l, int r) {
        if (l == 0 && r == 0) {
            ret.add(str);
            return;
        }
        
        if (l > 0) {
            backtrack(str + '(', ret, l - 1, r);
        }
        if (r > 0 && l < r) {
            backtrack(str + ')', ret, l, r - 1);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.