https://leetcode.com/contest/5/problems/frog-jump/
这个题目,还是有套路的,之前做过一道题,好像是贪心性质,就是每次可以跳多远,最后问能不能跳到最右边,一会找一下这道题(找到了,就是这个55. Jump Game)。然后这道题,差不多是相同的意思,但是每次只能跳3个或者2个,跳了之后还要判断那个位置有没有石头,然后还要记录上一次跳的间隔,然后我就想到了要用map做一个位置到index的映射,主要用于o(1)的查找,可以用unordered_map来做,然后每个位置还要记录上一次跳的间隔,但是不用记住上一次的位置,考虑可以多次转移,然后每一个位置用set记录,上次的间隔。最后想一下,数据范围也就1000,应该很容易的就过了,就这样。
1 class Solution { 2 public: 3 bool canCross(vector<int>& s) { 4 int n = s.size(); 5 if(n == 1) return 1; 6 if(s[0] + 1 != s[1]) return 0; 7 vector<bool> res(n + 1, 0); 8 res[1] = 1; 9 set<int> se; 10 set<int> a[n]; 11 map<int, int> m; 12 for (int i = 0; i < n; i++) {se.insert(s[i]); 13 m[s[i]] = i; 14 } 15 a[1].insert(1); 16 for (int i = 1; i < n - 1; i++) { 17 for (auto it = a[i].begin(); it != a[i].end(); it++) { 18 //cout << i << " " << *it << endl; 19 int cur = *it; 20 if(cur - 1 > 0) { 21 if(m.count(s[i] + cur - 1)) { 22 int t = m[s[i] + cur - 1]; 23 a[t].insert(cur - 1); 24 res[t] = 1; 25 } 26 } 27 if(m.count(s[i] + cur)) { 28 int t = m[s[i] + cur]; 29 a[t].insert(cur); 30 res[t] = 1; 31 } 32 if(m.count(s[i] + cur + 1)) { 33 int t = m[s[i] + cur + 1]; 34 a[t].insert(cur + 1); 35 res[t] = 1; 36 } 37 38 } 39 } 40 return res[n - 1]; 41 } 42 };