Java solution beats 90%


  • 0
    Z

    public class Solution {
    public List<String> generateParenthesis(int n) {
    List<String> ans = new ArrayList<>();
    char[] str = new char[n*2];

        build(ans, n, n, str, 0);
        
        return ans;
    }
    
    public void build(List<String> ans, int lefts, int rights, char[] str, int index) {
        if(lefts > rights) {
            return;
        } 
        
        if(index == str.length) {
            ans.add(new String(str));
            return;
        }
        
        if(lefts > 0) {
            str[index] = '(';
            build(ans,lefts-1,rights,str,index + 1);
        }
        
        str[index] = ')';
        build(ans,lefts,rights - 1,str,index + 1);
    }
    

    }


Log in to reply
 

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