我试图将二维递归问题转化为动态编程问题。但结果却不同。
以下是代码:
import edu.princeton.cs.algs4.*;
import java.util.Arrays;
public class Test {
public static double binomial(int N, int k, double p) {
if(N == 0 && k == 0) return 1.0;
if(N < 0 || k < 0) return 0.0;
return (1 - p)*binomial(N-1, k, p) + p*binomial(N-1, k-1, p);
}
public static double binomialm(int N, int k, double p) {
if(N < 0 || k < 0) return 0.0;
double[][] memory = new double[N+1][k+1];
memory[0][0] = 1.0;
memory[1][0] = 1 - p;
memory[0][1] = 0.0;
for(int i = 1; i <= N; i++) {
for(int j = 1; j <= k; j++) {
memory[i][j] = (1 - p)*memory[i-1][j] + p*memory[i-1][j-1];
}
}
return memory[N][k];
}
static public void main(String args[]) {
long stime, stime1, etime, etime1;
double r, r1;
stime = System.currentTimeMillis();
r = binomial(10, 5, 0.25);
etime = System.currentTimeMillis();
System.out.println("Regular binomial: result = " + r + ", time = " + (etime - stime));
stime1 = System.currentTimeMillis();
r1 = binomialm(10, 5, 0.25);
etime1 = System.currentTimeMillis();
System.out.println("Memoized binomial: result = " + r1 + ", time = " + (etime1 - stime1));
}
}
我真的无法弄清楚为什么结果会有所不同。他们在这里:
常规二项式:结果= 0.058399200439453125,时间= 0
记忆二项式:结果= 0.045421600341796875,时间= 0
我缺少一些浮点魔法吗?
答案 0 :(得分:1)
在您的memoized版本中,您的内部循环从j = 1
开始。因此,(2,0),(3,0),(4,0),......的值永远不会改变,它们在创建双数组时仍然是0.0。它们应该是1.0,-1.0,1.0,......
for(int i = 1; i <= N; i++) {
memory[i][0] = (1 - p)*memory[i-1][0];
for(int j = 1; j <= k; j++) {
memory[i][j] = (1 - p)*memory[i-1][j] + p*memory[i-1][j-1];
}
}