-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwater-and-jug-problem.rs
91 lines (84 loc) · 2.3 KB
/
water-and-jug-problem.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
impl Solution {
pub fn can_measure_water(jug1_capacity: i32, jug2_capacity: i32, target_capacity: i32) -> bool {
let mut set = std::collections::HashSet::<(i32, i32)>::new();
Self::dfs(
jug1_capacity,
jug2_capacity,
target_capacity,
0,
0,
&mut set,
)
}
fn dfs(
jug1_capacity: i32,
jug2_capacity: i32,
target_capacity: i32,
current_1: i32,
current_2: i32,
set: &mut std::collections::HashSet<(i32, i32)>,
) -> bool {
if set.contains(&(current_1, current_2)) {
return false;
}
set.insert((current_1, current_2));
if current_1 == target_capacity
|| current_2 == target_capacity
|| current_1 + current_2 == target_capacity
{
return true;
}
// 1清空
// 2清空
// 1装满
// 2装满
// 1到给2
// 2到给1
Self::dfs(
jug1_capacity,
jug2_capacity,
target_capacity,
0,
current_2,
set,
) || Self::dfs(
jug1_capacity,
jug2_capacity,
target_capacity,
current_1,
0,
set,
) || Self::dfs(
jug1_capacity,
jug2_capacity,
target_capacity,
jug1_capacity,
current_2,
set,
) || Self::dfs(
jug1_capacity,
jug2_capacity,
target_capacity,
current_1,
jug2_capacity,
set,
) || Self::dfs(
jug1_capacity,
jug2_capacity,
target_capacity,
current_1 - (jug2_capacity - current_2).max(0).min(current_1),
current_2 + (jug2_capacity - current_2).max(0).min(current_1),
set,
) || Self::dfs(
jug1_capacity,
jug2_capacity,
target_capacity,
current_1 + (jug1_capacity - current_1).max(0).min(jug2_capacity),
jug2_capacity - (jug1_capacity - current_1).max(0).min(jug2_capacity),
set,
)
}
}