ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

千问 LeetCode LCP 09. 最小跳跃次数 C语言实现

2026/8/21 22:10:33 拓冰建站 浏览量
千问    LeetCode LCP 09. 最小跳跃次数 C语言实现 解题思路本题的关键在于理解移动规则在位置 i每次操作只能二选一——向右跳到 i jump[i]固定距离或向左跳到 0 ~ i-1 的任意位置。目标是跳到 ≥ n 的位置。由于允许回跳不能简单贪心。BFS 保证第一次到达目标时步数最少。剪枝核心leftBound向左跳看似可以跳到任意左侧位置复杂度会退化为 O(n²)。但观察发现如果位置 j 在之前的 BFS 层已经被访问过再访问它不会得到更优解。因此维护一个 leftBound记录已被批量探索过的最左边界每次向左跳只需扫描 leftBound ~ cur-1 中未访问的位置每个位置最多入队一次均摊 O(n)。C 语言实现#include stdlib.h#include string.hint minJump(int* jump, int jumpSize) {if (jumpSize 0) return 0;int* dist (int*)malloc(jumpSize * sizeof(int));memset(dist, -1, jumpSize * sizeof(int));int* queue (int*)malloc(jumpSize * sizeof(int));int head 0, tail 0;dist[0] 0;queue[tail] 0;int leftBound 0; // 向左已探索到的最左边界while (head tail) {int cur queue[head];int step dist[cur];// 向右跳跳到 cur jump[cur]int rightPos cur jump[cur];if (rightPos jumpSize) {free(dist);free(queue);return step 1;}if (dist[rightPos] -1) {dist[rightPos] step 1;queue[tail] rightPos;}// 向左跳扫描 leftBound ~ cur-1 中未访问的位置for (int leftPos leftBound; leftPos cur; leftPos) {if (dist[leftPos] -1) {dist[leftPos] step 1;queue[tail] leftPos;}}if (cur leftBound) {leftBound cur;}}free(dist);free(queue);return -1;}算法详解状态定义dist[i] 从位置 0 到达位置 i 的最少操作次数。BFS 两层扩展1. 向右扩展从 cur 跳到 cur jump[cur]若越界则返回 step 12. 向左扩展从 cur 可以回跳到 0 ~ cur-1 任意位置但只处理 leftBound ~ cur-1 中未被访问过的。处理完后将 leftBound 更新为 cur为什么 leftBound 剪枝是正确的BFS 按层扩展先被访问的位置一定步数更少。当处理到位置 cur 时0 ~ leftBound-1 中的位置已经在更早的层被处理过或被标记为已访问再从 cur 回跳到它们不会得到更优解。因此只需扫描 leftBound ~ cur-1。复杂度- 时间O(n)。每个位置最多入队一次leftBound 单调递增向左扫描的总次数均摊为 O(n)- 空间O(n)。dist 数组 队列示例走读以 jump [2, 5, 1, 1, 1, 1] 为例n6初始: dist[0]0, leftBound0, 队列[0]处理 0 (step0):右跳: 022, dist[2]1, 队列[2]左跳: leftBound0, cur0, 无左侧位置leftBound0处理 2 (step1):右跳: 213, dist[3]2, 队列[3]左跳: leftBound0, cur2扫描 0~1: dist[0]已访问, dist[1]-1 → dist[1]2队列[3, 1]leftBound2处理 3 (step2):右跳: 314, dist[4]3, 队列[1, 4]左跳: leftBound2, cur3扫描 2~2: dist[2]已访问leftBound3处理 1 (step2):右跳: 156 ≥ 6, 越界! 返回 step1 3路径0 →(右跳) 2 →(左跳) 1 →(右跳) 6共 3 步。需要我帮你整理一份类似的带回退的最短路径题单吗比如 LeetCode 45「跳跃游戏 II」、LeetCode 1345「跳跃游戏 IV」等。