Very easy to understand Java backtracking solution


  • 0
    T
    public class Solution {
        
        public List<String> generateParenthesis(int n) {
            int open = 0;
            int close = 0;
            List<String> list = new ArrayList<>();
            helper("", open, close, n, list);
            return list;
            
        }
        
        private void helper(String temp, int open, int close, int n, List<String> list){
            if(open>n || close>n || close>open) return;
            if(open == n && close == n){
                list.add(temp);
                return;
            }
            
            if(open==close){
                helper(temp+"(", open+1, close, n, list);
            }else{
               helper(temp+"(", open+1, close, n, list) ;
               helper(temp+")", open, close+1, n, list);
            }
        }
    }

Log in to reply
 

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