class Solution { public List generateParenthesis(int n) { List result = new ArrayList<>(); // no of opening and closing brackets int open = n; int close = n; findBalancedParenthesis(open, close, result, ""); return result; } public void findBalancedParenthesis(int open, int close, List result, String temp) { // base condition: when both opening and closing brackets is finished, so valid string if(open == 0 && close == 0) { result.add(temp); return; } // choice of opening bracket if(open != 0) { findBalancedParenthesis(open-1, close, result, temp + '('); } // choice of closing bracket if(close > open) { findBalancedParenthesis(open, close-1, result, temp + ')'); } } }