```
int longestValidParentheses(string str)
{
int n=str.size();
if(n==0) return 0;
bool** dp=new bool*[n];
for(int i=0;i<n;i++)
dp[i]=new bool[n];
/*
for(int i=0;i<str.size();i++)
{
for(int j=0;j<str.size();j++)
{
cout<<dp[i][j]<<" ";
}
cout<<endl;
}*/
for(int i=0;i<=n-1;i++)
dp[i][i]=false;
int maxlen=0;
for(int i=0;i<=n-2;i++)
{
if(str[i]=='(' && str[i+1]==')')
dp[i][i+1]=true,maxlen=2;
else
dp[i][i+1]=false;
}
for(int length=3;length<=n;length++)
{
for(int i=0;i<=n-3;i++)
{
int j=i+length-1;
if(j>=n)
break;
dp[i][j]=false;
if(dp[i+1][j-1]==true && str[i]=='(' && str[j]==')')
{ dp[i][j]=true; maxlen=length;continue;}
for(int k=i;k<j;k++)
{
if(dp[i][k] && dp[k+1][j])
{ dp[i][j]=true;maxlen=length;break;}
}
}
}
for(int i=0;i<n;i++)
delete[] dp[i];
delete[] dp;
return maxlen;
}
```

I use three loop to get the best result, I think it's needed, but it TLE, in my local machine, costs 1078ms, for a very long string, also I find that global variables would be slower than heap, why? Also bool heap initialized with unexpected value.... This a dp solution, before I use stack to process it for one pass, but tried to modify logic codes for thousands of times, then I find it it was DP, my tears.......

Could anybody help me?