leetcode 403. 青蛙过河

题目:403. 青蛙过河 - 力扣(LeetCode)

O(n^2)水题

cpp 复制代码
class Solution {
public:
    bool canCross(vector<int>& stones) {
        int n = (int) stones.size();
        vector<vector<int>> f;
        f.resize(n);
        f[0].push_back(1);
        int64_t temp;
        for (int i = 0; i < n - 1; i++) {
            vector<int>& t = f[i];
            sort(t.begin(), t.end());
            int j = i + 1;
            for (int k = 0; k < t.size(); k++) {
                if (k > 0 && t[k] == t[k - 1]) {
                    continue;
                }
                temp = stones[i];
                temp += t[k];
                if (temp > stones[j]) {
                    while (j < n - 1 && temp >= stones[j + 1]) {
                        j++;
                    }
                }
                if (stones[i] + t[k] == stones[j]) {
                    if (j == n - 1) {
                        return true;
                    }
                    if (t[k] > 1) {
                        f[j].push_back(t[k] - 1);
                    }
                    f[j].push_back(t[k]);
                    f[j].push_back(t[k] + 1);
                    continue;
                }
            }
        }
        return false;
    }
};
相关推荐
文丑颜不良啊11 小时前
LeetCode2981~3000题目解析
java·leetcode
文丑颜不良啊17 小时前
LeetCode3001~3020题目解析
java·leetcode
Pniubi1 天前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode2761~2780题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2841~2860题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2921~2940题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2901~2920题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2861~2880题目解析
java·leetcode
文丑颜不良啊3 天前
LeetCode2821~2840题目解析
java·leetcode
Pniubi3 天前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表