Java recursive solution beats 90%


  • 0
    M
    public class Solution {
        private List<String> list = new ArrayList<>();
        public List<String> generateParenthesis(int n) {
            if(n <= 0){
                return list;
            }
            
            char[] str = new char[n*2];
            generate(n, n, str, 0);
            return list;
        }
        
        private void generate(int left, int right, char[] str, int index){
            // checks
            if(left < 0 || right < left){
                return;
            }
            
            if(left == 0 && right == 0){
                list.add(String.copyValueOf(str));
            }
            
            if(left > 0){
                str[index] = '(';
                generate(left-1, right, str, index+1);
            }
            if(right > left){
                str[index] = ')';
                generate(left, right-1, str, index+1);
            }
        }
    }
    

Log in to reply
 

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