Example: Generate Parenthesis - rFronteddu/general_wiki GitHub Wiki

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> out = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        solve (out, sb, 0, 0, n);
        return out;
    }
    
    void solve (List<String> out, StringBuilder sb, int oCount, int cCount, int n) {
        if (oCount == n && cCount == n) {
            out.add (sb.toString());    
            return;
        }
        
        if (oCount < n) {
            sb.append('(');
            solve (out, sb, oCount+1, cCount, n);
            sb.deleteCharAt (sb.length() - 1);
        }
        
        if (cCount < oCount) {
            sb.append(')');
            solve (out, sb, oCount, cCount+1, n);
            sb.deleteCharAt (sb.length() - 1);
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️