【发布时间】: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;
}
【问题讨论】: