Ways to Express an Integer as Sum of Powers — LeetCode 2787 Python Solution
- Problem
- #2787
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(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.