-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathWater and Jug Problem.cpp
38 lines (28 loc) · 1.26 KB
/
Water and Jug Problem.cpp
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
class Solution {
public:
bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
if(targetCapacity > jug1Capacity + jug2Capacity)
return false;
vector<int> dp(jug1Capacity + jug2Capacity + 1, -1);
return helper(0, jug1Capacity, jug2Capacity, targetCapacity, dp);
}
bool helper(int tmp, int &jug1Capacity, int &jug2Capacity, int &targetCapacity, vector<int> &dp)
{
if(tmp < 0 || tmp > jug1Capacity + jug2Capacity)
return false;
if(tmp == targetCapacity)
return true;
if(dp[tmp] != -1)
return dp[tmp];
dp[tmp] = false;
if(helper(tmp + jug1Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))
return dp[tmp] = true;
if(helper(tmp - jug1Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))
return dp[tmp] = true;
if(helper(tmp + jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))
return dp[tmp] = true;
if(helper(tmp - jug2Capacity, jug1Capacity, jug2Capacity, targetCapacity, dp))
return dp[tmp] = true;
return dp[tmp] = false;
}
};