class{ public List<String> generateParenthesis(int n){ List<String> ans = new ArrayList<String>(); backtrace(0,0,"",n,ans); return ans; } publicvoidbacktrace(int left, int right, String s, int n, List<String> ans){ if(s.length() == 2*n){ ans.add(s); return ; } if(left < n) backtrace(left+1, right, s+"(", n, ans); if(right < left) backtrace(left, right+1, s+")", n, ans); } }
Using backtrace method.
left means the number of ( , right means the number of ) . Each step, if left < n , this means that we should add ( to current string s , if right < left , this means that we should add ) to current string s.
近期评论