LeetCode 题解工作台
特别的排列
给你一个下标从 0 开始的整数数组 nums ,它包含 n 个 互不相同 的正整数。如果 nums 的一个排列满足以下条件,我们称它是一个特别的排列: 对于 0 的下标 i ,要么 nums[i] % nums[i+1] == 0 ,要么 nums[i+1] % nums[i] == 0 。 请你返…
4
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们注意到题目中数组的长度最大不超过 ,因此,我们可以用一个二进制整数来表示当前的状态,其中第 位为 表示数组中的第 个数已经被选取,为 表示数组中的第 个数还未被选取。 我们定义 表示当前选取的整数状态为 ,且最后一个选取的整数下标为 的方案数。初始时 ,答案为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums ,它包含 n 个 互不相同 的正整数。如果 nums 的一个排列满足以下条件,我们称它是一个特别的排列:
- 对于
0 <= i < n - 1的下标i,要么nums[i] % nums[i+1] == 0,要么nums[i+1] % nums[i] == 0。
请你返回特别排列的总数目,由于答案可能很大,请将它对 109 + 7 取余 后返回。
示例 1:
输入:nums = [2,3,6] 输出:2 解释:[3,6,2] 和 [2,6,3] 是 nums 两个特别的排列。
示例 2:
输入:nums = [1,4,3] 输出:2 解释:[3,1,4] 和 [4,1,3] 是 nums 两个特别的排列。
提示:
2 <= nums.length <= 141 <= nums[i] <= 109
解题思路
方法一:状态压缩动态规划
我们注意到题目中数组的长度最大不超过 ,因此,我们可以用一个二进制整数来表示当前的状态,其中第 位为 表示数组中的第 个数已经被选取,为 表示数组中的第 个数还未被选取。
我们定义 表示当前选取的整数状态为 ,且最后一个选取的整数下标为 的方案数。初始时 ,答案为 。
考虑 ,如果当前只有一个数被选取,那么 。否则,我们可以枚举上一个选择的数的下标 ,如果 与 对应的数满足题目要求,那么 可以从 转移而来。即:
最终答案即为 。注意答案可能很大,需要对 取模。
时间复杂度 ,空间复杂度 。其中 为数组的长度。
class Solution:
def specialPerm(self, nums: List[int]) -> int:
mod = 10**9 + 7
n = len(nums)
m = 1 << n
f = [[0] * n for _ in range(m)]
for i in range(1, m):
for j, x in enumerate(nums):
if i >> j & 1:
ii = i ^ (1 << j)
if ii == 0:
f[i][j] = 1
continue
for k, y in enumerate(nums):
if x % y == 0 or y % x == 0:
f[i][j] = (f[i][j] + f[ii][k]) % mod
return sum(f[-1]) % mod
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates a clear understanding of dynamic programming with bitmasking.
- question_mark
The candidate successfully applies state transition methods to the problem.
- question_mark
The candidate efficiently manages large numbers using modulo operations.
常见陷阱
外企场景- error
Forgetting to apply the modulo operation at each step, leading to overflow.
- error
Incorrectly handling the state transitions, such as failing to check the divisibility condition between consecutive elements.
- error
Not efficiently managing bitmasking, resulting in redundant calculations.
进阶变体
外企场景- arrow_right_alt
Considering additional constraints such as larger arrays or different divisibility conditions.
- arrow_right_alt
Applying different dynamic programming strategies for state transitions.
- arrow_right_alt
Optimizing the solution for faster execution with larger inputs.