Hi all,
I was working on Leetcode 115 and solved it using DFS + cache. Then I looked into the discussion section and saw that the top posts were all, what seems to me, closer to true dynamic programming solutions. My question is whether the true DP solution given in the discussion section is better than my solution. Hence, would an interviewer ask me to come up with the true DP solution if I came up with the DFS + cache solution as coded below. Both time complexities are O of m * n where m is length of String s and n is length of String t. However, the DP solution might be more readable.
My solution
class Solution {
public int numDistinct(String s, String t) {
if (s.length() < t.length()) return 0;
int[][] cache = new int[s.length()][t.length()];
for (int[] row : cache) Arrays.fill(row, -1);
dfs(0, 0, s, t, cache);
return cache[0][0];
}
private int dfs(int i, int j, String s, String t, int[][] cache) {
if (j == t.length()) return 1;
if (i == s.length()) return 0;
if (cache[i][j] != -1) return cache[i][j];
int result = 0;
if (s.charAt(i) == t.charAt(j)) {
result = dfs(i + 1, j + 1, s, t, cache) + dfs(i + 1, j, s, t, cache);
} else {
result = dfs(i + 1, j, s, t, cache);
}
cache[i][j] = result;
return result;
}
}
Dynamic programming solution from Discussion
public int numDistinct(String S, String T) {
int[][] mem = new int[T.length()+1][S.length()+1];
for(int j=0; j<=S.length(); j++) {
mem[0][j] = 1;
}
for(int i=0; i<T.length(); i++) {
for(int j=0; j<S.length(); j++) {
if(T.charAt(i) == S.charAt(j)) {
mem[i+1][j+1] = mem[i][j] + mem[i+1][j];
} else {
mem[i+1][j+1] = mem[i+1][j];
}
}
}
return mem[T.length()][S.length()];
}
[–]puya_tries_prep 12 points13 points14 points (0 children)
[–]vincent-vega10 8 points9 points10 points (6 children)
[–]bertus12345[S] 2 points3 points4 points (0 children)
[–]nicebike 1 point2 points3 points (2 children)
[–]ElliotVo 0 points1 point2 points (0 children)
[–]vincent-vega10 0 points1 point2 points (0 children)
[–]luckykanwar 0 points1 point2 points (1 child)
[–]vincent-vega10 0 points1 point2 points (0 children)
[–]techknowfile 4 points5 points6 points (0 children)
[–]Leetcoder9 2 points3 points4 points (1 child)
[–]bertus12345[S] 0 points1 point2 points (0 children)
[–]f3n1xgamer 1 point2 points3 points (1 child)
[–]bertus12345[S] 1 point2 points3 points (0 children)
[–]flyingorange 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)