I would appreciate an intuitive way to find the time complexity of dynamic programming problems. Can anyone explain me “#subproblems * time/subproblem”? I am not able to grok it.
Code for LCS -
public static String findLCS(String str1, String str2 ) {
// If either string is empty, return the empty string
if(null == str1 || null == str2)
return "";
if("".equals(str1) || "".equals(str2)) {
return "";
}
// are the last characters identical?
if(str1.charAt(str1.length()-1) == str2.charAt(str2.length()-1)) {
// yes, so strip off the last character and recurse
return findLCS(str1.substring(0, str1.length() -1), str2.substring(0, str2.length()-1)) + str1.substring(str1.length()-1, str1.length());
} else {
// no, so recurse independently on (str1_without_last_character, str2)
// and (str1, str2_without_last_character)
String opt1 = findLCS(str1.substring(0, str1.length() -1), str2);
String opt2 = findLCS(str1, str2.substring(0, str2.length()-1));
// return the longest LCS found
if(opt1.length() >= opt2.length())
return opt1;
else
return opt2;
}
}
I am just providing the actual code instead of pseudo code (i hope pseudo code or the algo is pretty self explanatory from above)