【问题标题】:Calculate time complexity for Distinct Subsequences计算不同子序列的时间复杂度
【发布时间】:2016-03-24 04:09:20
【问题描述】:

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

        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;
        }

【问题讨论】:

    标签: algorithm time-complexity


    【解决方案1】:

    这里的时间复杂度是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)

    【讨论】:

    • 如果我们去掉“Dictionary memoery”,时间复杂度是多少?
    • 由于您要删除memoisation step,时间复杂度将变为Exponential,即O(2 ^ SizeOf(t))
    • 在最坏的情况下:在递归调用的每一步,您可以做出 2 个决定,即是否在答案中包含字符串 t 的当前字母表,您可以通过以下方式执行此操作将idxt 变量增加一或保持不变,因此您有2 ^ n 可能的生成搜索空间的方法,其中n 是字符串t 的大小。
    猜你喜欢
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多