Return the number of waysncan be expressed as the sum of thexth
_power ofunique positive integers, in other words, the number of sets of unique integers _[n1, n2, ..., nk]wheren = n1x + n2x + ... + nkx.
Since the result can be very large, return it modulo 10^9 + 7.
For example, if n = 160 and x = 3, one way to express n is `n = 23 + 33
Input: n =10, x =2Output: 1Explanation: We can express n as the following: n =32+12=10.It can be shown that it is the only way to express 10 as the sum of the 2nd power of unique integers.
This is a variation of the subset sum problem, where each number can be used at most once, and the numbers are their x-th powers. We use dynamic programming to count the number of ways to sum to n using unique powers.
classSolution {
public:int numberOfWays(int n, int x) {
constint MOD =1e9+7;
vector<int> pows;
for (int k =1; ; ++k) {
int v = pow(k, x);
if (v > n) break;
pows.push_back(v);
}
vector<int> dp(n+1);
dp[0] =1;
for (int v : pows) {
for (int i = n; i >= v; --i) {
dp[i] = (dp[i] + dp[i-v]) % MOD;
}
}
return dp[n];
}
};
import java.util.*;
classSolution {
publicintnumberOfWays(int n, int x) {
int mod = 1_000_000_007;
List<Integer> pows =new ArrayList<>();
for (int k = 1; ; k++) {
int v = (int)Math.pow(k, x);
if (v > n) break;
pows.add(v);
}
int[] dp =newint[n+1];
dp[0]= 1;
for (int v : pows) {
for (int i = n; i >= v; i--) {
dp[i]= (dp[i]+ dp[i-v]) % mod;
}
}
return dp[n];
}
}
classSolution {
funnumberOfWays(n: Int, x: Int): Int {
val mod = 1_000_000_007
val pows = mutableListOf<Int>()
var k = 1while (true) {
val v = Math.pow(k.toDouble(), x.toDouble()).toInt()
if (v > n) break pows.add(v)
k++ }
val dp = IntArray(n+1)
dp[0] = 1for (v in pows) {
for (i in n downTo v) {
dp[i] = (dp[i] + dp[i-v]) % mod
}
}
return dp[n]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defnumberOfWays(self, n: int, x: int) -> int:
MOD =10**9+7 pows = []
k =1whileTrue:
v = k ** x
if v > n:
break pows.append(v)
k +=1 dp = [0] * (n+1)
dp[0] =1for v in pows:
for i in range(n, v-1, -1):
dp[i] = (dp[i] + dp[i-v]) % MOD
return dp[n]
impl Solution {
pubfnnumber_of_ways(n: i32, x: i32) -> i32 {
let m =1_000_000_007;
letmut pows =vec![];
letmut k =1;
while k.pow(x asu32) <= n {
pows.push(k.pow(x asu32));
k +=1;
}
let n = n asusize;
letmut dp =vec![0; n+1];
dp[0] =1;
for&v in&pows {
let v = v asusize;
for i in (v..=n).rev() {
dp[i] = (dp[i] + dp[i-v]) % m;
}
}
dp[n]
}
}