forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.rs
65 lines (56 loc) · 1.42 KB
/
Solution.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
impl Solution {
#[allow(dead_code)]
pub fn is_interleave(s1: String, s2: String, s3: String) -> bool {
let n = s1.len();
let m = s2.len();
if s1.len() + s2.len() != s3.len() {
return false;
}
let mut record = vec![vec![-1; m + 1]; n + 1];
Self::dfs(
&mut record,
n,
m,
0,
0,
&s1.chars().collect(),
&s2.chars().collect(),
&s3.chars().collect()
)
}
#[allow(dead_code)]
fn dfs(
record: &mut Vec<Vec<i32>>,
n: usize,
m: usize,
i: usize,
j: usize,
s1: &Vec<char>,
s2: &Vec<char>,
s3: &Vec<char>
) -> bool {
if i >= n && j >= m {
return true;
}
if record[i][j] != -1 {
return record[i][j] == 1;
}
// Set the initial value
record[i][j] = 0;
let k = i + j;
// Let's try `s1` first
if i < n && s1[i] == s3[k] && Self::dfs(record, n, m, i + 1, j, s1, s2, s3) {
record[i][j] = 1;
}
// If the first approach does not succeed, let's then try `s2`
if
record[i][j] == 0 &&
j < m &&
s2[j] == s3[k] &&
Self::dfs(record, n, m, i, j + 1, s1, s2, s3)
{
record[i][j] = 1;
}
record[i][j] == 1
}
}