首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算不同子序列的时间复杂度

计算不同子序列的时间复杂度
EN

Stack Overflow用户
提问于 2016-03-24 04:09:20
回答 1查看 151关注 0票数 1

问题来自leetcode,我想出了下面的代码,但我很难找到它的时间复杂性。知道如何计算它的时间复杂度吗?(如果没有字典记忆呢)

代码语言:javascript
复制
        public int NumDistinct (string s, string t)
        {
            if (string.IsNullOrEmpty (s) && string.IsNullOrEmpty (t))
                return 1;
            else if (string.IsNullOrEmpty (s) || string.IsNullOrEmpty (t))
                return 0;

            return FindSequences (s, 0, t, 0);
        }

        Dictionary<string, int> memoery = new Dictionary<string, int> ();

        private int FindSequences (string s, int idxs, string t, int idxt)
        {
            if (idxt == t.Length)
                return 1;
            else if (idxs == s.Length)
                return 0;

            string key = string.Format ("{0}-{1}", idxs, idxt);
            if (memoery.ContainsKey (key))
                return memoery [key];

            int result = 0;
            if (s [idxs] == t [idxt]) {
                result = FindSequences (s, idxs + 1, t, idxt + 1) + FindSequences (s, idxs + 1, t, idxt);
            } else {
                result = FindSequences (s, idxs + 1, t, idxt);
            }
            memoery.Add (key, result);
            return result;
        }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-24 05:21:33

这里的时间复杂性是O(SizeOf(s) * SizeOf(t))。对于Dynamic Programming Solutions,您可以使用不同状态的数量来计算时间复杂度,这里的状态量是SizeOf(s) * sizeOf(t)

动态规划使用了Memoisation的概念,即存储状态的结果,这样当我们遇到相同的状态时,就可以使用它,因此我们有效地不进行冗余计算,因为状态经常重复,而当它们重复时,我们使用之前计算的结果来降低时间复杂度。

还请注意,时间复杂性还取决于Look up tableDP Table,在上述情况下,这是一个Dictionary,因此您还必须考虑Dictionary Look upDictionary Insertion的时间,从而有效地使复杂性达到:

O(SizeOf(s) * SizeOf(t) * Time to look Up or insert in Dictionary)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36193137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档