Share my bit solution


  • 0
    L

    public class Solution {

    public IList<string> GenerateParenthesis(int n) {
        IList<string> result = new List<string>();
        
        if(n == 0)
            return result;
        
        
        string maxString = "";
        string minString = "";
        
        for(int i =0;i<n;i++)
        {
            maxString= maxString+"0";
            maxString = "1"+maxString;
            minString += "10";
        }
        //1111.....000000.....
        long maxValue = Convert.ToInt64(maxString,2);
        //10101010101......
        long minValue = Convert.ToInt64(minString,2);
        
        for(long i=minValue;i<=maxValue;i=i+2)
        {
            if(Check1s(i, n))
            {
                result.Add(Convert.ToString(i,2).Replace("1","(").Replace("0",")"));
            }
        }
        
        return result;
    }
    
    
        private bool Check1s(long x,int n)
        {
            int C1 = n;
            int C0 = n;
            while (x != 0)
            {
                if (x>>1<<1 == x)
                {
                    C0--;
                }
                else
                {
                    C1--;
                }
    
                if (C1 < 0 || C0 < 0 || C1 < C0)
                {
                    return false;
                }
                x = x >> 1;
            }
    
            return true;
        }
    

    }


Log in to reply
 

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