Very Simple Java code Backtracking


  • 0
    B
    public List<String> generateParenthesis(int n){
            List<String> list = new ArrayList<>();
            recursive(n-1, n, "(", list);
            return list;
        }
    
        public void recursive(int open, int close, String parenthesis, List list){
            if(open == 0 && close == 0)
                list.add(parenthesis);
            else if(open < 0 || close == 0 || open > close)
                return;
            else{
                recursive(open-1, close, parenthesis+"(", list);
                recursive(open, close-1, parenthesis+")", list);
            }
        }
    
    

    I uesd the backtracking method


Log in to reply
 

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