Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        dfs(2*n, 0, "", res);
        return res;
    }
    
    private void dfs(int n, int count, String tmp, List<String> res) {
        if (n == 0 || count < 0 ) {
            // The parenthesis string becomes invalid when count less than 0.
            // Thus the valid parenthesis string is generated when only n and count equal to 0. 
            if (count == 0) {
                res.add(tmp);
            }
            return;
        }
        dfs(n - 1, count + 1, tmp + "(", res);
        dfs(n - 1, count - 1, tmp + ")", res);
    }
}