Why (()())(()()) not valid for n = 6?


  • 0
    C

    My code generated one more string for n = 6 which is (()())(()()). My code is below. Can someone help please? Thanks!

    public List<String> generateParenthesis(int n) {
        List<String> lst = new LinkedList<>();
        if (n == 0) return lst;
        if (n == 1) {
            lst.add("()");
            return lst;
        }
        List<String> prevLst = generateParenthesis(n-1);
        for (int i = 0; i < prevLst.size(); i++) {
            String prevStr = prevLst.get(i);
            if (!lst.contains(prevStr+"()")) lst.add(prevStr+"()");
            if (!lst.contains("()"+prevStr)) lst.add("()"+prevStr);
            if (!lst.contains("(" + prevStr + ")")) lst.add("(" + prevStr + ")");
    
            for (int j = 0; j < prevStr.length()-1; j++) {
                if (prevStr.charAt(j) == '(' && prevStr.charAt(j+1) == ')') {
                    String temp = prevStr.substring(0, j+1) + "()" + prevStr.substring(j+1, prevStr.length());
                    if (!lst.contains(temp)) lst.add(temp);
                }
            }
        }
        return lst;
    }

Log in to reply
 

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