LeetCode 题解工作台
将一个数字表示成幂的和的方案数
给你两个 正 整数 n 和 x 。 请你返回将 n 表示成一些 互不相同 正整数的 x 次幂之和的方案数。换句话说,你需要返回互不相同整数 [n 1 , n 2 , ..., n k ] 的集合数目,满足 n = n 1 x + n 2 x + ... + n k x 。 由于答案可能非常大,请你将…
1
题型
8
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示在前 个正整数中选取一些数的 次幂之和等于 的方案数,初始时 $f[0][0] = 1$,其余均为 。答案为 。 对于每个正整数 ,我们可以选择不选它或者选它:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你两个 正 整数 n 和 x 。
请你返回将 n 表示成一些 互不相同 正整数的 x 次幂之和的方案数。换句话说,你需要返回互不相同整数 [n1, n2, ..., nk] 的集合数目,满足 n = n1x + n2x + ... + nkx 。
由于答案可能非常大,请你将它对 109 + 7 取余后返回。
比方说,n = 160 且 x = 3 ,一个表示 n 的方法是 n = 23 + 33 + 53 。
示例 1:
输入:n = 10, x = 2 输出:1 解释:我们可以将 n 表示为:n = 32 + 12 = 10 。 这是唯一将 10 表达成不同整数 2 次方之和的方案。
示例 2:
输入:n = 4, x = 1 输出:2 解释:我们可以将 n 按以下方案表示: - n = 41 = 4 。 - n = 31 + 11 = 4 。
提示:
1 <= n <= 3001 <= x <= 5
解题思路
方法一:动态规划
我们定义 表示在前 个正整数中选取一些数的 次幂之和等于 的方案数,初始时 ,其余均为 。答案为 。
对于每个正整数 ,我们可以选择不选它或者选它:
- 不选它:此时方案数为 ;
- 选它:此时方案数为 (前提是 )。
因此状态转移方程为:
注意到答案可能非常大,我们需要对 取余。
时间复杂度 ,空间复杂度 。其中 是题目中给定的整数。
class Solution:
def numberOfWays(self, n: int, x: int) -> int:
mod = 10**9 + 7
f = [[0] * (n + 1) for _ in range(n + 1)]
f[0][0] = 1
for i in range(1, n + 1):
k = pow(i, x)
for j in range(n + 1):
f[i][j] = f[i - 1][j]
if k <= j:
f[i][j] = (f[i][j] + f[i - 1][j - k]) % mod
return f[n][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * n^(1/x)) due to iterating all possible integers whose xth power is <= n and updating dp. Space complexity is O(n) since only a one-dimensional DP array is needed. |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Focus on unique usage of integers to avoid overcounting in the DP table.
- question_mark
Emphasize proper iteration order for state transitions to ensure correctness.
- question_mark
Clarify handling of modulo arithmetic to prevent integer overflow.
常见陷阱
外企场景- error
Using integers multiple times instead of enforcing uniqueness.
- error
Iterating dp array from low to high, which breaks the uniqueness constraint.
- error
Failing to apply modulo 10^9 + 7 correctly in each update step.
进阶变体
外企场景- arrow_right_alt
Count combinations allowing repeated integers (classic coin change variant).
- arrow_right_alt
Compute the number of ways to express n as sum of factorials instead of powers.
- arrow_right_alt
Extend the problem to find all actual sets, not just the count.