自顶向下 (递归实现)
公式:
class Program
{
static void Main(string[] args)
{
int n = 5;
int[] p = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
Console.WriteLine(UpDown(0, p));
Console.WriteLine(UpDown(1, p));
Console.WriteLine(UpDown(2, p));
Console.WriteLine(UpDown(3, p));
Console.WriteLine(UpDown(4, p));
Console.WriteLine(UpDown(5, p));
Console.WriteLine(UpDown(6, p));
Console.WriteLine(UpDown(7, p));
Console.WriteLine(UpDown(8, p));
Console.WriteLine(UpDown(9, p));
Console.WriteLine(UpDown(10, p));
Console.ReadKey();
}
public static int UpDown(int n,int[] p)
{
if (n == 0) return 0;
int tempMaxPrice = 0;
for (int i = 1; i < n + 1; i++)
{
int maxPrice = p[i] + UpDown(n - i, p);
if (maxPrice > tempMaxPrice)
{
tempMaxPrice = maxPrice;
}
}
return tempMaxPrice;
}
}
带缓存的自顶向下
class Program
{
static void Main(string[] args)
{
int[] resultPrice = new int[11];
int[] p = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
Console.WriteLine(UpDown(0, p,resultPrice));
Console.WriteLine(UpDown(1, p, resultPrice));
Console.WriteLine(UpDown(2, p, resultPrice));
Console.WriteLine(UpDown(3, p, resultPrice));
Console.WriteLine(UpDown(4, p, resultPrice));
Console.WriteLine(UpDown(5, p, resultPrice));
Console.WriteLine(UpDown(6, p, resultPrice));
Console.WriteLine(UpDown(7, p, resultPrice));
Console.WriteLine(UpDown(8, p, resultPrice));
Console.WriteLine(UpDown(9, p, resultPrice));
Console.WriteLine(UpDown(10, p, resultPrice));
Console.ReadKey();
}
private static int UpDown(int n, int[] p,int[] result)
{
if (n == 0) return 0;
if(result[n]!=0)
{
return result[n];
}
int tempMaxPrice = 0;
for (int i = 1; i <= n; i++)
{
int maxPrice = p[i] + UpDown(n - i, p,result);
if (maxPrice > tempMaxPrice)
{
tempMaxPrice = maxPrice;
}
}
result[n] = tempMaxPrice;
return tempMaxPrice;
}
}
自底向上-动态规划
class Program
{
static void Main(string[] args)
{
int[] resultPrice = new int[11];
int[] p = { 0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 };
Console.WriteLine(BottomUp(0,p,resultPrice));
Console.WriteLine(BottomUp(1, p, resultPrice));
Console.WriteLine(BottomUp(2, p, resultPrice));
Console.WriteLine(BottomUp(3, p, resultPrice));
Console.WriteLine(BottomUp(4, p, resultPrice));
Console.WriteLine(BottomUp(5, p, resultPrice));
Console.WriteLine(BottomUp(6, p, resultPrice));
Console.WriteLine(BottomUp(7, p, resultPrice));
Console.WriteLine(BottomUp(8, p, resultPrice));
Console.WriteLine(BottomUp(9, p, resultPrice));
Console.WriteLine(BottomUp(10, p, resultPrice));
Console.ReadKey();
}
private static int BottomUp(int n,int[] p,int[] result)
{
int tempMaxPrice = -1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
int maxPrice = p[j] + result[i - j];
if(maxPrice>tempMaxPrice)
{
tempMaxPrice = maxPrice;
}
}
result[i] = tempMaxPrice;
}
return result[n];
}
}