Ways to Express an Integer as Sum of Powers — LeetCode 2787 Python Solution

MediumDynamic Programming
Problem
#2787
Reading time
2 min

The problem

Given two positive integers n and x. Return the number of ways n can be expressed as the sum of the xth power of unique positive integers, in other words, the number of sets of unique integers [n1, n2, ..., nk] where n = n1x + n2x + ...

Example

Input
n = 10, x = 2
Output
1
Explanation
We can express n as the following: n = 32 + 12 = 10.

Python solution

Python
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

MeasureComplexity
TimeO(n^2)
SpaceO(n^2), where n is the given integer in the auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2787. Ways to Express an Integer as Sum of Powers is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2787. Ways to Express an Integer as Sum of Powers?
LeetCode 2787. Ways to Express an Integer as Sum of Powers is rated Medium on LeetCode.
What is the time complexity of LeetCode 2787. Ways to Express an Integer as Sum of Powers?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2787. Ways to Express an Integer as Sum of Powers?
The Python solution on this page uses O(n^2), where n is the given integer in the auxiliary space.
What topics does LeetCode 2787. Ways to Express an Integer as Sum of Powers cover?
LeetCode 2787. Ways to Express an Integer as Sum of Powers is tagged Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview