double R(int N, int x[206], int i, int c){
if (memo[i][c] != 0) return memo[i][c];
if (i==N){
if (c>=23) return 1;
else return 0;
}
double s;
s = R(N,x,i+1,c+x[i]);
s += R(N,x,i+1,c-x[i]);
memo[i][c] = s;
return s;
}
现在这是一个递归的memoized函数,但我希望将其转换为迭代等效DP,如果可能的话。或者这是我能做到的唯一方法吗?
答案 0 :(得分:0)
理论上,您可以将任何递归方法转换为迭代方法。所以,是的,这段代码也可以。
有关它的更多信息,请参阅此主题:https://stackoverflow.com/questions/931762/can-every-recursion-be-converted-into-iteration
答案 1 :(得分:0)
由于x可以包含任意整数,因此您应该为 R
的值<{1}}计算c
,其中i
是固定的。
一些代码解释:
// case where i == N
for (int c = INT_MIN; c < INT_MAX; ++c) {
memo[N][c] = (c>=23) ? 1 : 0;
}
for (int k = N - 1; k >= i; --k) {
for (int c_ = INT_MIN; c_ < INT_MAX; ++c_) {
memo[k][c_] = memo[k+1][c_ + x[k]] + memo[k+1][c_ - x[k]];
}
}
return memo[i][c];
对x
的值进行一些限制可能有助于改善结果。