动态规划算法

算法介绍:

背包问题01

代码实现

package com.hy.tenalgorithm;

/**
* 动态规划算法
*
* @author hanyong
* @date 2020/7/14 20:06
*/
public class DymanicAlgorithm {
public static void main(String[] args) {
int[] w = {1, 4, 3}; //物品的重量
int[] val = {1500, 3000, 2000}; //物品的价值
//背包的容量
int m = 4;
//物品的种类个数
int n = val.length;

int[][] v = new int[n + 1][m + 1];
//创建一个数组记录商品放入情况
int[][] path = new int[n + 1][m + 1];
for (int i = 0; i < v.length; i++) {
v[i][0] = 0;
}

for (int i = 0; i < v[0].length; i++) {
v[0][i] = 0;
}

for (int i = 1; i < v.length; i++) {
for (int j = 1; j < v[0].length; j++) {
if (w[i - 1] > j) {
v[i][j] = v[i - 1][j];
} else {
//v[i][j] = Math.max(v[i - 1][j], val[i - 1] + v[i - 1][j - w[i - 1]]);
if (v[i - 1][j] < val[i - 1] + v[i - 1][j - w[i - 1]]) {
v[i][j] = val[i - 1] + v[i - 1][j - w[i - 1]];

path[i][j] = 1;

} else {
v[i][j] = v[i - 1][j];
}
}
}
}


//遍历查看分配结果是否正确
for (int i = 0; i < v.length; i++) {
for (int j = 0; j < v[0].length; j++) {
System.out.print(v[i][j] + " ");
}
System.out.println();
}

/* for (int i = 0; i < path.length; i++) {
for (int j = 0; j < path[i].length; j++) {
if (path[i][j] == 1) {
System.out.printf("第%d个商品放入到背包\n", i);
}
}
}*/

int i = path.length - 1;
int j = path[0].length - 1;
while (i > 0 && j > 0) {
if (path[i][j] == 1) {
System.out.printf("第%d个商品放入到背包\n", i);
j -= w[i - 1];
}
i--;
}

}

}

你可能感兴趣的:(动态规划算法)