关于0、1背包问题 求大神看看哪里错了
public class Knapsack {
public static int [] [] knapsack(int [] w,int [] v,int c){
int n=w.length;
int [] [] m=new int [n+1] [c+1];
for (int i = 1; i < n+1; i++) {
m [i] [0]=0;
}
for (int j = 1; j < c+1; j++) {
m [0] [j]=0;
}
for (int i = 1; i < n; i++)
for (int j = 1; j < c; j++) {
m[i][j]=m[i-1][j];
if(w[i-1]<=j)
if(v[i-1]+m[i-1] [j-w[i-1]]>m[i-1][j])
m[i][j]=v[i-1]+m[i-1][j-w[i-1]];
}
return m;
}
for(i=1;i<n+1;i++)
for(j=1;j<m+1;j++)
{
if(w[i]<=j){
if(p[i]+c[i-1][j-w[i]]>c[i-1][j])
c[i][j]=p[i]+c[i-1][j-w[i]];
else
c[i][j]=c[i-1][j];
}else
c[i][j]=c[i-1][j];
}
return(c[n][m]);
public static int [] buildSolution(int [] [] m,int [] w,int c){
int j=c,n=w.length;
int [] x=new int[n];
for (int i = n; i >1; i--)
if(m[i][j]==m[i-1][j])
x[i-1]=0;
else{
x[i-1]=1;
j-=w[i-1];
}
return x;
}
}
测试类
public class Test {
public static void main(String[] args) {
int w []={2,3,4,5};
int v []={3,4,5,7};
int [] [] m;
int [] x;
m=Knapsack.knapsack(w, v, 9);
x=Knapsack.buildSolution(m, w, 9);
for (int i = 0; i < 4; i++)
System.out.println(x[i]+" ");
System.out.println();
}
} 01背包问题
[解决办法]
给兄台提俩建议吧:写个思路或代码里写点注释,方便大家伙学习。
[解决办法]
看到这代码就头大,csdn中有专门放代码的地方 都不知道吗?
public class Knapsack {
public static int [] [] knapsack(int [] w,int [] v,int c){
int n=w.length;
int [] [] m=new int [n+1] [c+1];
for (int i = 1; i < n+1; i++) {
m [i] [0]=0;
}
for (int j = 1; j < c+1; j++) {
m [0] [j]=0;
}
for (int i = 1; i < n; i++)
for (int j = 1; j < c; j++) {
m[i][j]=m[i-1][j];
if(w[i-1]<=j)
if(v[i-1]+m[i-1] [j-w[i-1]]>m[i-1][j])
m[i][j]=v[i-1]+m[i-1][j-w[i-1]];
}
return m;
}
for(i=1;i<n+1;i++)
for(j=1;j<m+1;j++)
{
if(w[i]<=j){
if(p[i]+c[i-1][j-w[i]]>c[i-1][j])
c[i][j]=p[i]+c[i-1][j-w[i]];
else
c[i][j]=c[i-1][j];
}else
c[i][j]=c[i-1][j];
}
return(c[n][m]);
public static int [] buildSolution(int [] [] m,int [] w,int c){
int j=c,n=w.length;
int [] x=new int[n];
for (int i = n; i >1; i--)
if(m[i][j]==m[i-1][j])
x[i-1]=0;
else{
x[i-1]=1;
j-=w[i-1];
}
return x;
}
}