问题:
public int backPackII(int m, int[] a, int[] v) {
int n = a.length;
int f[][] = new int[n+1][m+1];
int i, j;
f[0][0] = 0;
for(i=1; i<=n; i++){
f[0][i] = -1;
}
for(i=1; i<n; i++){
for(j=0; j<=m; j++){
f[i][j] = f[i-1][j];
if(j >= a[i] && f[i-1][j-a[i]] != -1){
f[i][j] = Math.max(f[i][j], f[i][j-a[i]]+v[i]);
}
}
}
int exchange = f[n][0];
for(i=1; i<=m; i++){
if(exchange < f[old_i][i]){
exchange = f[old_i][i];
}
}
return exchange;
}
也可以用滚动数组:
public int backPackII(int m, int[] a, int[] v) {
// write your code here
int f[][] = new int[2][m+1];
int i, j, old_i=0, new_i=1, exchange;
int len = a.length;
f[0][0] = 0;
for(i=1; i<=len; i++){
f[0][i] = -1;
}
for(i=0; i<len; i++){
for(j=0; j<=m; j++){
f[new_i][j] = f[old_i][j];
if(j >= a[i] && f[old_i][j-a[i]]!=-1){
f[new_i][j] = Math.max(f[new_i][j], f[old_i][j-a[i]]+v[i]);
}
}
exchange = old_i;
old_i = new_i;
new_i = exchange;
}
exchange = f[old_i][0];
for(i=1; i<=m; i++){
if(exchange < f[old_i][i]){
exchange = f[old_i][i];
}
}
return exchange;
}