Showing TLE but successfully submitted in leetcode


#1

long long value(string s,int n)
{
long long sum = 0;
for(int i=0;i<n;i++)
{
sum = sum + (s[i]-48)*(1<<i);
}
return sum;
}

bool solve(string s,vector&v,int n)
{
int i;
long long k = value(s,n);

if(find(v.begin(),v.end(),k)!=v.end()) return false;

v.push_back(k);
long long size = pow(2,n);
if(v.size()==size)
return true;

for(i=0;i<n;i++)
{
    if(s[i]=='0')
    {
        s[i] =   '1'; 
        
        bool b = solve(s,v,n);
        if(b) return true;
        
        s[i] = '0';
    }
    
    else
    {
           s[i] =   '0'; 
        
        bool b = solve(s,v,n);
        if(b) return true;
        
        s[i] = '1';
    }
}

return false;

}

vector Solution::grayCode(int A) {
vector<int ans;
long long x = pow(2 , A) , i;
for(i=0 ; i < x ; i++)
{
int j = i/2;
ans.push_back(i^j);
}
return ans;
}