在 Java 中:
如果您需要列出组合:
static void sumToValue(int limit, int sum, int count, List<Integer> resultIP) {
if (limit >= 0 && sum == 0 && count == 0) {
// print resultIP, because it is one of the answers.
System.out.println("sum(" + Arrays.toString(resultIP.toArray()) + ")");
} else if (limit <= 0 || count == 0 || sum <= 0) {
// not what we want
return;
} else {
// Two options: choose current limit number or not
sumToValue(limit - 1, sum, count, resultIP);// Not choose the limit
// number
// or choose the limit number
List<Integer> resultNext = new ArrayList<Integer>(resultIP);// copy
// resultIP
resultNext.add(limit);
sumToValue(limit - 1, sum - limit, count - 1, resultNext);
}
}
如果你只需要计数:
static void sumToValueCount(int limit, int sum, int count) {
int dp[][][] = new int[limit + 1][sum + 1][count + 1];
for (int i = 0; i <= limit; i++) {
for (int j = 0; j <= sum; j++) {
for (int k = 0; k <= count; k++) {
if (j == 0 && k == 0) {
dp[i][j][k] = 1;
} else if (i == 0 || j <= 0 || k == 0) {
dp[i][j][k] = 0;
} else {
// check to prevent negative index
if (j - i >= 0) {
// two options: choose the number or not choose the number
dp[i][j][k] = dp[i - 1][j - i][k - 1] + dp[i - 1][j][k];
} else {
dp[i][j][k] = dp[i - 1][j][k];
}
}
}
}
}
System.out.println(dp[limit][sum][count]);
}
在这样的主函数调用中:
//limit is 45, sum is the sum we want, count is 6 referring to the question.
sumToValue(45, 255, 6, new ArrayList<Integer>());
sumToValueCount(45, 255, 6);