simple,standard backtracking java solution


  • 0
    C
    public List<String> generateParenthesis(int n) {
            ArrayList<String> result = new ArrayList<String>();
            helper(n,result,new String("()"));
            return result;
        }
        private void helper(int n, ArrayList<String> result, String curr){
            if(curr.length()/2 == n) {
                if(!result.contains(curr))
                    result.add(new String(curr));
            }else{
                for(int i=0;i<curr.length();i++){
                    String pre = new String(curr);
                    if((curr.charAt(i) == '(' && curr.charAt(i+1) == ')') || (i+1<curr.length() && (curr.charAt(i) == ')' && curr.charAt(i+1) == ')')) || i+1 == curr.length()){
                        curr  = curr.substring(0,i+1) + "()" + curr.substring(i+1,curr.length());
                        helper(n,result,curr);
                        curr = pre;
                    }
                }
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.