LeetCode 题解工作台

将一个数字表示成幂的和的方案数

给你两个 正 整数 n 和 x 。 请你返回将 n 表示成一些 互不相同 正整数的 x 次幂之和的方案数。换句话说,你需要返回互不相同整数 [n 1 , n 2 , ..., n k ] 的集合数目,满足 n = n 1 x + n 2 x + ... + n k x 。 由于答案可能非常大,请你将…

category

1

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

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

bolt

答案摘要

我们定义 表示在前 个正整数中选取一些数的 次幂之和等于 的方案数,初始时 $f[0][0] = 1$,其余均为 。答案为 。 对于每个正整数 ,我们可以选择不选它或者选它:

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个  整数 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 <= 300
  • 1 <= x <= 5
lightbulb

解题思路

方法一:动态规划

我们定义 f[i][j]f[i][j] 表示在前 ii 个正整数中选取一些数的 xx 次幂之和等于 jj 的方案数,初始时 f[0][0]=1f[0][0] = 1,其余均为 00。答案为 f[n][n]f[n][n]

对于每个正整数 ii,我们可以选择不选它或者选它:

  • 不选它:此时方案数为 f[i1][j]f[i-1][j]
  • 选它:此时方案数为 f[i1][jix]f[i-1][j-i^x](前提是 jixj \geq i^x)。

因此状态转移方程为:

f[i][j]=f[i1][j]+(jix?f[i1][jix]:0)f[i][j] = f[i-1][j] + (j \geq i^x ? f[i-1][j-i^x] : 0)

注意到答案可能非常大,我们需要对 109+710^9 + 7 取余。

时间复杂度 O(n2)O(n^2),空间复杂度 O(n2)O(n^2)。其中 nn 是题目中给定的整数。

1
2
3
4
5
6
7
8
9
10
11
12
13
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]
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

将一个数字表示成幂的和的方案数题解:状态·转移·动态规划 | LeetCode #2787 中等