今天记录一下我所理解的01背包问题动态规划求解思路
思路如下
m代表背包承重
wp代表物品重量和物品价值数组
设置全局变量result数组记录当前重量和存放物品个数最大价值
两个for从1开始遍历,设置0位置默认为0
如果当前物品重量大于背包重量
result[tempM, tempI] = result[tempM, tempI - 1];
最大价值数组减去这个物品不受影响
或者开始比较放或者不放这个物品哪个最大价值高
int maxValue1 = result[tempM - w[tempI], tempI - 1] + p[tempI];
int maxValue2 = result[tempM, tempI - 1];
if (maxValue1 > maxValue2)
{
result[tempM, tempI] = maxValue1;
}
else
{
result[tempM, tempI] = maxValue2;
}
通过这个函数得出最大价值最佳方案,放进result数组中
最后return
这就是我对动态规划的理解
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace _01背包问题_自底向上法_动态规划_
{
class Program
{
static void Main(string[] args)
{
int m;
int[] w = { 0, 3, 4, 5 };
int[] p = { 0, 4, 5, 6 };
Console.WriteLine(BottomUp(10,3,w,p));
Console.WriteLine(BottomUp(3,3,w,p));
Console.WriteLine(BottomUp(4, 3, w, p));
Console.WriteLine(BottomUp(5, 3, w, p));
Console.WriteLine(BottomUp(7, 3, w, p));
Console.ReadKey();
}
public static int[,] result=new int[11,4];
public static int BottomUp(int m, int i, int[] w, int[] p)
{
if (result[m, i] != 0) return result[m, i];
for (int tempM = 1; tempM < m+1; tempM++)
{
for (int tempI = 1; tempI < i+1; tempI++)
{
if(result[tempM,tempI]!=0)continue;
if (w[tempI] > tempM)
{
result[tempM, tempI] = result[tempM, tempI - 1];
}
else
{
int maxValue1 = result[tempM - w[tempI], tempI - 1] + p[tempI];
int maxValue2 = result[tempM, tempI - 1];
if (maxValue1 > maxValue2)
{
result[tempM, tempI] = maxValue1;
}
else
{
result[tempM, tempI] = maxValue2;
}
}
}
}
return result[m, i];
}
}
}