Really short and effective java solution


  • 0
    R
    public class Solution {
        public List<String> generateParenthesis(int n) {
            List<String> list = new ArrayList<>();
            buildList(list, 0, n, "");
            return list;
        }
        
    // opened : number of opened parenthesis in s that do not have their closing one yet
    // remaining : number of opened parenthesis that I can still add to s
        private void buildList(List<String> list, int opened, int remaining, String s){
            if(remaining == 0 && opened == 0){ // I cannot add anymore '(' and they are all closed
                list.add(s);
            } else{
                if(remaining > 0) buildList(list, opened+1, remaining-1, s+'(');
                if(opened > 0) buildList(list, opened-1, remaining, s + ')');
            }
        }
    }
    ''''

Log in to reply
 

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