Concise JAVA solution


  • 0
    C
    public class Solution{
        private List<String> list = new ArrayList<String>();
        private String[] brackets = new String[]{"(", ")"};
        
        public List<String> generateParenthesis(int n){
            permute("", 0, 0, n);
            return list;          
        }
        
        private void permute(String prefix, int depth, int val, int n){
            if(val > n || val < 0) return;
            if(depth == 2 * n){
                if(val == 0){
                    list.add(prefix);
                }return;
            }
            for(int i = 0; i < brackets.length; i++){
                permute(prefix + brackets[i], depth + 1, i == 0 ? val + 1 : val - 1, n);
            }
        }
    }

Log in to reply
 

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