Dynamic programming (rod cutting) using recursion in java
So, I'm trying to make a simple implementation of a dynamic programming
problem in java work. The method is the cut-rod method of Algorithms,
third edition (by Rivest et al) chapter 15 here is my code -
public static double cutRod(double[] p, int n){
if(n==0)return 0;
double q = -1000;
for(int i=0;i<n;i++){
q = Math.max( q, p[i]+cutRod(p,n-i));
}
return q;
}
public static void main(String[] args) throws FileNotFoundException,
IOException{
double[] p = {1,5,8,9,10,17,17,20,24,30};
double val = cutRod(p,10);
System.out.println(val);
}
When I try and run this, I get a stack overflow error. Even when I try and
debug it (I'm using netbeans), it pauses a while on the first recursive
call and then gives me a stack overflow error. Any ideas?
No comments:
Post a Comment