我已经被困了一个多小时,我已经对动态编程问题有了正确的解决方案,但由于某些原因它太慢了。即使我使用的是C ++,我仍然会在hackerrank的测试用例上获得超时(我希望Java会出现这种问题)。
Here is the Coin Change Problem
这是我的问题代码:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
N - The amount of change that should be created.
M - The number of elements in the C array.
C[] - The array of possible coins to use. Coins can be reused.
i - The index of the coin to begin with, as to not
repeat combinations already used.
*/
unsigned long long coinChangeCombinations(int N, int M, int C[], int i) {
unsigned long long combinations = 0;
for (; i < M; i++) {
int c = C[i];
if (N == c) {
combinations++;
} else if (N > c) {
combinations += coinChangeCombinations(N - c, M, C, i);
}
}
return combinations;
}
int main() {
unsigned long long N, M;
cin >> N;
cin >> M;
int C[M];
for (int i = 0; i < M; i++) {
int c;
cin >> c;
C[i] = c;
}
cout << coinChangeCombinations(N, M, C, 0) << endl;
return 0;
}
大多数讨论都集中在迭代解决方案上 - 迭代总是比递归更快吗?在这种情况下,我认为迭代解决方案没有理由比递归更快。当然,递归会占用更多内存,但这不是我遇到的问题。