#2787
Ways to Express an Integer as Sum of Powers
MediumDynamic ProgrammingDynamic ProgrammingCombinatorial Counting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * m)Space O(n)
We can use dynamic programming to build up the number of ways to express each integer up to n using unique integers raised to the x-th power. This avoids redundant calculations and efficiently counts combinations.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP table where dp[k][j] represents the number of ways to express k using unique integers up to j.
- 2Step 2: Iterate through each integer j from 1 to the maximum integer whose x-th power is <= n.
- 3Step 3: For each k from n down to the x-th power of j, update dp[k] by adding dp[k - j^x].
solution.py12 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def sum_of_powers(n, x):
5 dp = [0] * (n + 1)
6 dp[0] = 1
7 max_base = int(n**(1/x))
8 for j in range(1, max_base + 1):
9 power = j ** x
10 for k in range(n, power - 1, -1):
11 dp[k] = (dp[k] + dp[k - power]) % MOD
12 return dp[n]ℹ
Complexity note: The time complexity is O(n * m), where m is the number of unique integers whose x-th power is less than or equal to n. This is efficient as we only compute valid combinations once.
- 1Dynamic programming allows us to build solutions incrementally.
- 2Unique integers mean we can't reuse numbers, which simplifies our state transitions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.