Interleaving String LeetCode solution in C++

1
/* index shifted by 1 because when memoization applied negative index can't be
2
* passed as arg for function */
3
class Solution {
4
public:
5
bool f(int i, int n, int m, string &s1, string &s2, string &s3, vector<vector<int>> &dp) {
6
cout << i << n << m << endl;
7
if (i == 0) return true;
8
if (n == 0 && m == 0) return false;
9

10
if (dp[n][m] != -1) return dp[n][m];
11

12
bool isMatchFoundS1 = false;
13
if (n > 0 && s1[n - 1] == s3[i - 1]) isMatchFoundS1 = f(i - 1, n - 1, m, s1, s2, s3, dp);
14

15
bool isMatchFoundS2 = false;
16
if (m > 0 && s2[m - 1] == s3[i - 1]) isMatchFoundS2 = f(i - 1, n, m - 1, s1, s2, s3, dp);
17

18
return dp[n][m] = isMatchFoundS1 || isMatchFoundS2;
19
}
20

21
bool isInterleave(string s1, string s2, string s3) {
22
int b = s1.size();
23
int c = s2.size();
24
int a = s3.size();
25
if (b + c != a) return false;
26

27
vector<vector<int>> dp(b + 1, vector<int>(c + 1, -1));
28

29
return f(a, b, c, s1, s2, s3, dp);
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0