| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.WaysToExpressAnIntegerAsSumOfPowers; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class WaysToExpressAnIntegerAsSumOfPowersDynamicProgramming : IWaysToExpressAnIntegerAsSumOfPowers |
| | 16 | | { |
| | 17 | | private const int Mod = 1_000_000_007; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n^(1 + 1/x)) |
| | 21 | | /// Space complexity - O(n) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="n"></param> |
| | 24 | | /// <param name="x"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public int NumberOfWays(int n, int x) |
| 2 | 27 | | { |
| 2 | 28 | | var dp = new long[n + 1]; |
| | 29 | |
|
| 2 | 30 | | dp[0] = 1; |
| | 31 | |
|
| 18 | 32 | | for (var i = 1; i <= n; i++) |
| 8 | 33 | | { |
| 8 | 34 | | var power = Pow(i, x); |
| | 35 | |
|
| 8 | 36 | | if (power > n) |
| 1 | 37 | | { |
| 1 | 38 | | break; |
| | 39 | | } |
| | 40 | |
|
| 72 | 41 | | for (var j = n; j >= power; j--) |
| 29 | 42 | | { |
| 29 | 43 | | dp[j] = (dp[j] + dp[j - power]) % Mod; |
| 29 | 44 | | } |
| 7 | 45 | | } |
| | 46 | |
|
| 2 | 47 | | return (int)dp[n]; |
| 2 | 48 | | } |
| | 49 | |
|
| | 50 | | private static int Pow(int value, int exponent) |
| 8 | 51 | | { |
| 8 | 52 | | var result = 1; |
| | 53 | |
|
| 40 | 54 | | for (var i = 0; i < exponent; i++) |
| 12 | 55 | | { |
| 12 | 56 | | result *= value; |
| 12 | 57 | | } |
| | 58 | |
|
| 8 | 59 | | return result; |
| 8 | 60 | | } |
| | 61 | | } |