Easy to understand Java Recursive solution


  • 0
    W
    public List<String> generateParenthesis(int n) {
            Set<String> set = new LinkedHashSet<String>();
            if(n == 1) {
                set.add("()");
            } else {
                List<String> previousList =  generateParenthesis(n - 1);
                for(String str: previousList) {
                    for(int i = 0; i < str.length(); i++) {
                        set.add(str.substring(0, i) + "()" + str.substring(i, str.length()));
                    }
                }
            }
            return new ArrayList(set);
        }
    

Log in to reply
 

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