C# 艾博霍比亚

C# 艾博霍比亚,c#,dynamic-programming,memoization,C#,Dynamic Programming,Memoization,我正在努力 我有一个解决方案,如下所示,但我得到了超出时间限制的错误。我想知道为什么这段代码效率低下,因为我在做备忘录 namespace Aibohphobia { class Test { static Dictionary<string, int> memo = new Dictionary<string, int>(); static int Main(string[] args) {

我正在努力

我有一个解决方案,如下所示,但我得到了超出时间限制的
错误。我想知道为什么这段代码效率低下,因为我在做备忘录

namespace Aibohphobia
{
    class Test
    {
        static Dictionary<string, int> memo = new Dictionary<string, int>();
        static int Main(string[] args)
        {
            string num = Console.ReadLine();
            int N = int.Parse(num);
            string input = string.Empty;
            for (int i = 0; i < N; i++)
            {
                memo = new Dictionary<string, int>();
                input = Console.ReadLine();
                int count = new Test().insert(input, 0, input.Length - 1);
                Console.WriteLine(count);
            }
            return 0;
        }

        int insert(string input, int start, int end)
        {
            int count = 0;
            var key = start + "_" + end;

            if (start >= end)
                return 0;            
            if (memo.ContainsKey(key))
                return memo[key];
            if (input[start] == input[end])
            {
                count += insert(input, start + 1, end - 1);
            }
            else
            {
                int countLeft = 1 + insert(input, start + 1, end);
                int countRight = 1 + insert(input, start, end - 1);
                count += Math.Min(countLeft, countRight);
            }

            memo.Add(key, count);
            return count;
        }    
  }
}
namespace-Aibohphobia
{
课堂测试
{
静态字典备忘录=新字典();
静态int Main(字符串[]args)
{
string num=Console.ReadLine();
int N=int.Parse(num);
字符串输入=string.Empty;
对于(int i=0;i=结束)
返回0;
if(备忘录集装箱箱(钥匙))
返回备忘录[键];
如果(输入[开始]==输入[结束])
{
计数+=插入(输入,开始+1,结束-1);
}
其他的
{
int countLeft=1+insert(输入,开始+1,结束);
int countRight=1+插入(输入、开始、结束-1);
count+=Math.Min(countLeft,countRight);
}
备注。添加(键、计数);
返回计数;
}    
}
}

您正在将结果存储在
字典中,字典本质上是一个哈希表。这意味着每次您想要检索给定键的值时,必须计算该键的哈希函数

在这种情况下,由于密钥的类型是
string
,因此哈希函数的计算肯定会减慢执行速度。我建议您在
int[][]矩阵
中记录DP的值,因此您可以更快地检索所需的值

为了实现这一点,您必须弄清楚如何将
字符串
映射到
整数
。您可以在这里找到一个关于如何实现这一点的简短教程:,作者在这里解释了简单的字符串哈希技术