我正在解决这个具体的问题AIBOHP,并使用基于检查长度为 i 的子字符串起始位置为 1 的末尾的 dp 方法。尽管我的时间复杂度在 O(n^2) 范围内,但由于空间占用过大,如果我动态声明它就会出现 RTE,如果我将其声明为全局静态,则会超时,需要减少它,因为 dp 大小可以是 6100 * 6100。有什么建议可以优化下面的代码以实现此目的。
问题描述如下:
问题描述如下:
He now asks the doctors to insert the minimum number of characters needed to make S a palindrome. Help the doctors accomplish this task.
For instance, if S = "fft", the doctors should change the string to "tfft", adding only 1 character.
我的代码是:
static int dp[6101][6101];
main()
{
int tc;
scanf("%d",&tc);
while(tc--)
{
char s[6102];
scanf("%s",s);
int len=strlen(s);
memset(dp,0,sizeof dp);
for(int i=1;i<len;i++)
for(int j=0,k=i;k<len;k++,j++)
dp[j][k]=(s[j]==s[k])?dp[j+1][k-1]:min(dp[j][k-1],dp[j+1][k])+1;
printf("%d\n",dp[0][len-1]);
}
return 0;
}
for (int i = 0; i < 6101; i++) memset(dp[i], 0, 6101*sizeof(int));
替代双重循环。 - Bernhard Barker