我无法优化following dynamic programming problem: 这是我对following test cases问题的JAVA解决方案。在更高的递归级别上超出限制。我无法理解在这种情况下如何实现memoization。任何帮助将不胜感激。
import java.util.*;
public class ProblemD {
static class Fireworks{
boolean occupied;
int dir;
public Fireworks(boolean occupied,int dir){
this.occupied=occupied;
this.dir=dir;
}
}
public static void fireworks(Fireworks f[][],int i,int j,int levels[],int n){
if(n<levels.length){
for(int k=1;k<levels[n];k++){
if(f[i][j].dir==0){
f[i+1][j]=new Fireworks(true,0);
i=i+1;
}
else if(f[i][j].dir==45){
f[i+1][j-1]=new Fireworks(true,45);
i=i+1;
j=j-1;
}
else if(f[i][j].dir==90){
f[i][j-1]=new Fireworks(true,90);
j=j-1;
}
else if(f[i][j].dir==135){
f[i-1][j-1]=new Fireworks(true,135);
i=i-1;
j=j-1;
}
else if(f[i][j].dir==180){
f[i-1][j]=new Fireworks(true,180);
i=i-1;
}
else if(f[i][j].dir==225){
f[i-1][j+1]=new Fireworks(true,225);
i=i-1;
j=j+1;
}
else if(f[i][j].dir==270){
f[i][j+1]=new Fireworks(true,270);
j=j+1;
}
else{
f[i+1][j+1]=new Fireworks(true,315);
i=i+1;
j=j+1;
}
}
//n++;
if(f[i][j].occupied && n<levels.length-1){
if(f[i][j].dir==0){
f[i+1][j-1]=new Fireworks(true,45);
f[i+1][j+1]=new Fireworks(true,315);
fireworks(f,i+1,j-1,levels,n+1);
fireworks(f,i+1,j+1,levels,n+1);
return;
}
else if (f[i][j].dir==45){
f[i][j-1]=new Fireworks(true,90);
f[i+1][j]=new Fireworks(true,0);
fireworks(f,i,j-1,levels,n+1);
fireworks(f,i+1,j,levels,n+1);
return;
}
else if(f[i][j].dir==90){
f[i+1][j-1]=new Fireworks(true,45);
f[i-1][j-1]=new Fireworks(true,135);
fireworks(f,i+1,j-1,levels,n+1);
fireworks(f,i-1,j-1,levels,n+1);
return;
}
else if(f[i][j].dir==135){
f[i][j-1]=new Fireworks(true,90);
f[i-1][j]=new Fireworks(true,180);
fireworks(f,i,j-1,levels,n+1);
fireworks(f,i-1,j,levels,n+1);
return;
}
else if(f[i][j].dir==180){
f[i-1][j-1]=new Fireworks(true,135);
f[i-1][j+1]=new Fireworks(true,225);
fireworks(f,i-1,j-1,levels,n+1);
fireworks(f,i-1,j+1,levels,n+1);
return;
}
else if(f[i][j].dir==225){
f[i-1][j]=new Fireworks(true,180);
f[i][j+1]=new Fireworks(true,270);
fireworks(f,i-1,j,levels,n+1);
fireworks(f,i,j+1,levels,n+1);
return;
}
else if(f[i][j].dir==270){
f[i-1][j+1]=new Fireworks(true,225);
f[i+1][j+1]=new Fireworks(true,315);
fireworks(f,i-1,j+1,levels,n+1);
fireworks(f,i+1,j+1,levels,n+1);
return;
}
else {
f[i+1][j]=new Fireworks(true,0);
f[i][j+1]=new Fireworks(true,270);
fireworks(f,i+1,j,levels,n+1);
fireworks(f,i,j+1,levels,n+1);
return;
}
}
}
else{
return;
}
}
public static void main(String[] args){
Fireworks f[][];
f=new Fireworks[500][500];
for(int i=0;i<500;i++){
for(int j=0;j<500;j++){
f[i][j]=new Fireworks(false,0);
}
}
Scanner sc=new Scanner(System.in);
int start=250;
int n=sc.nextInt();
int levels[]=new int[n];
f[start][start].occupied=true;
f[start][start].dir=0;
for(int i=0;i<n;i++){
levels[i]=sc.nextInt();
}
fireworks(f,start,start,levels,0);
int count=0;
for(int i=0;i<500;i++){
for(int j=0;j<500;j++){
if(f[i][j].occupied){
System.out.println(i+" "+j);
count++;
}
}
}
System.out.println(count);
}
}