-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsoln.cpp
33 lines (31 loc) · 899 Bytes
/
soln.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
class Solution {
public:
bool canCross(vector<int>& stones) {
memo.clear();
return helper(stones, 0, 0);
}
bool helper(vector<int> & stones, int pos, int k) {
int key = k | (pos << 11);
auto it = memo.find(key);
if (it != memo.end()) return it->second;
int n = stones.size();
bool ans = false;
for(int i = pos + 1; i < n; ++i) {
int gap = stones[i] - stones[pos];
if (gap < k - 1) continue;
else if (gap > k + 1) {
memo[key] = false;
return false;
} else {
if (helper(stones, i, gap)) {
memo[key] = true;
return true;
}
}
}
memo[key] = (pos == n - 1);
return pos == n - 1;
}
private:
unordered_map<int, int> memo;
};