Can Someone pointout what is wrong with this code


  • 0
    D
        public List<String> generateParenthesis(int n) {
            String s="";
            List<String> ls=new ArrayList<String>();
            if(n<=0)
            {
                return ls;
            }
            for(int i=0;i<n;i++)
            {
                s=s+"()";
            }
            permute(s.toCharArray(),0,ls);
            return ls;
        }
        
        public void permute(char[] chr,int start,List<String> ls)
        {
            if(isValid(chr) && !isPresent(new String(chr),ls))
            {
                ls.add(new String(chr));
            }
            for(int i=start;i<chr.length;i++)
            {
                swap(chr,start,i);
                permute(chr,i+1,ls);
                swap(chr,start,i);
            }
        }
        
        public void swap(char[] chr,int i,int j)
        {
            char c=chr[i];
            chr[i]=chr[j];
            chr[j]=c;
        }
        
        public boolean isValid(char[] chr)
        {
            int open=0;
            for(int i=0;i<chr.length;i++)
            {
                if(chr[i]=='(')
                {
                    open++;
                }
                else
                {
                    open--;
                }
                if(open<0)
                {
                    return false;
                }
            }
            return true;
        }
        
        public boolean isPresent(String str, List<String> source)
        {
            for(String s:source)
            {
                if(s.equals(str))
                {
                    return true;
                }
            }
            return false;
        }
    }```

Log in to reply
 

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