LeetCode 题解工作台

统计异或值为给定值的路径数目

给你一个大小为 m x n 的二维整数数组 grid 和一个整数 k 。 你的任务是统计满足以下 条件 且从左上格子 (0, 0) 出发到达右下格子 (m - 1, n - 1) 的路径数目: 每一步你可以向右或者向下走,也就是如果格子存在的话,可以从格子 (i, j) 走到格子 (i, j + 1…

category

4

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个大小为 m x n 的二维整数数组 grid 和一个整数 k 。

你的任务是统计满足以下 条件 且从左上格子 (0, 0) 出发到达右下格子 (m - 1, n - 1) 的路径数目:

  • 每一步你可以向右或者向下走,也就是如果格子存在的话,可以从格子 (i, j) 走到格子 (i, j + 1) 或者格子 (i + 1, j) 。
  • 路径上经过的所有数字 XOR 异或值必须 等于 k 。

请你返回满足上述条件的路径总数。

由于答案可能很大,请你将答案对 109 + 7 取余 后返回。

 

示例 1:

输入:grid = [[2, 1, 5], [7, 10, 0], [12, 6, 4]], k = 11

输出:3

解释:

3 条路径分别为:

  • (0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2)
  • (0, 0) → (1, 0) → (1, 1) → (1, 2) → (2, 2)
  • (0, 0) → (0, 1) → (1, 1) → (2, 1) → (2, 2)

示例 2:

输入:grid = [[1, 3, 3, 3], [0, 3, 3, 2], [3, 0, 1, 1]], k = 2

输出:5

解释:

5 条路径分别为:

  • (0, 0) → (1, 0) → (2, 0) → (2, 1) → (2, 2) → (2, 3)
  • (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → (2, 3)
  • (0, 0) → (1, 0) → (1, 1) → (1, 2) → (1, 3) → (2, 3)
  • (0, 0) → (0, 1) → (1, 1) → (1, 2) → (2, 2) → (2, 3)
  • (0, 0) → (0, 1) → (0, 2) → (1, 2) → (2, 2) → (2, 3)

示例 3:

输入:grid = [[1, 1, 1, 2], [3, 0, 3, 2], [3, 0, 2, 2]], k = 10

输出:0

 

提示:

  • 1 <= m == grid.length <= 300
  • 1 <= n == grid[r].length <= 300
  • 0 <= grid[r][c] < 16
  • 0 <= k < 16
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间complexity depends on the number of cells `m * n` and the number of possible XOR values (16), resulting in a time complexity of O(m * n * 16). Space complexity is similarly O(m * n * 16) due to the DP table size.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for a candidate's ability to apply dynamic programming to state transitions effectively.

  • question_mark

    Assess whether the candidate understands the necessity of tracking XOR states in paths.

  • question_mark

    Check if the candidate handles the grid traversal and transition properly, avoiding unnecessary recomputation.

warning

常见陷阱

外企场景
  • error

    Candidates may forget to handle boundary conditions when transitioning from cells that are not top or left.

  • error

    Some may struggle with the memory management of the 3D DP table, especially when the grid size is large.

  • error

    Not considering the XOR of previous steps correctly may lead to incorrect path calculations.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Variant where grid size increases but the XOR value remains small.

  • arrow_right_alt

    Grid with higher values of `k` where optimization strategies like bitmasking could help.

  • arrow_right_alt

    Variant involving negative or different range of values in the grid.

help

常见问题

外企场景

统计异或值为给定值的路径数目题解:状态·转移·动态规划 | LeetCode #3393 中等