problem:https://leetcode.com/problems/odd-even-jump/
我的做法用的是order_map(记录下一个跳跃位置) + 记忆搜索(避免重复计算某一点能否跳到终点),速度偏慢,优点是写起来简单,容易理解。
估计前者可以优化为使用栈做,后者可以改为非递归的。
class Solution { public: vector<vector<int>> dp; vector<vector<int>> next; bool canJump(vector<int>& A, int i, int op) { if (i == A.size() - 1) { return true; } if (dp[i][op] != 2) { return dp[i][op]; } int j = next[i][op]; if (j == -1) { dp[i][op] = false; } else { dp[i][op] = canJump(A, j, !op); } return dp[i][op]; } int oddEvenJumps(vector<int>& A) { int n = A.size(); map<int, int> s; dp.resize(n, vector<int>(2, 2)); next.resize(n, vector<int>(2, -1)); for (int i = n - 1; i >= 0; i--) { auto it = s.lower_bound(A[i]); if (it != s.end()) { next[i][0] = it->second; } if (it != s.end() && it->first == A[i]) { next[i][1] = next[i][0]; } else if (it != s.begin()) { it = prev(it); next[i][1] = it->second; } s[A[i]] = i; } int res = 0; for (int i = 0; i < A.size(); i++) { if (canJump(A, i, 0)) { res++; } } return res; } };