classSolution {publicList<String> generateParenthesis(int n) {// as long as the str during generation has ')' no more than '(', the final string is valid// make sure '(' is always more than or equal to ')' in the substring// '(' cannot be more than nList<String> result =newLinkedList<>();dfs(result,"",0,0,n);return result; }privatevoiddfs(List<String> li,String str,int left,int right,int n){if (right == n){li.add(str);return; }// add '(' is safe if left<nif (left<n){dfs(li, str+'(', left+1, right, n); }// add ')' is safe if right<leftif (left>right){dfs(li, str+')', left, right+1,n); } }}