题目:在一个mxn的棋盘的每一个格子里面都放有一个礼物,每一个礼物都有一定的价值(价值大于0)。你可以从棋盘的左上角开始拿格子里的礼物,并且每次向右或者向下移动一格,直到到达棋盘的右下角。给定一个棋盘及上面的礼物,请计算你最多能拿到多少价值的礼物。
1 10 3 8
12 2 9 6
5 7 4 11
3 7 16 5
思路:
按照{1,12,5,7,7,16,5}的顺序就能够拿到最大价值的礼物。这个问题可以用动态规划来解决问题。定义一个函数f(i,j)表示到达坐标为(i,j)的格子能拿到的礼物的最大值。按照题目的要求,可以有两种路径到达(i,j),一种是通过点(i,j-1),另一种就是(i-1,j),也就是左边和上面的两个点,那么选择这两个点中f函数值最大的点就可以了。所以计算f(i,j)=max(f(i,j-1),f(i-1,j))+gift[i][j]。上面的是递归的思路,会有一些重复的计算,那么按照循环的方式来写代码会好一些。
代码1:
int getMax_solution1(const int*values, int rows, int cols)
{
if (values == nullptr || rows <= 0 || cols <= 0)
return 0;
int**maxValues = new int*[rows];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
int left = 0;
int up = 0;
if (i > 0)
up = maxValues[i - 1][j];
if (j > 0)
left = maxValues[i][j - 1];
maxValues[i][j] = max(up, left) + values[i*cols + j];
}
}
int maxValue = maxValues[rows - 1][cols - 1];
for (int i = 0; i < rows; i++)
delete maxValues[i];
delete maxValues;
return maxValue;
}
这个代码还有优化的空间,应为某个点的最大礼物价值相关的数据只依赖左边以及上面的格子,所以第i-2行以及更上面的格子没有必要保存下来。
如上图所示,只需要保存4前面的5和7,以及上面的9和6就行了,数组的长度为矩阵的列数n。
代码2:
#include <iostream>
#include<algorithm>
using namespace std;
int getMax_solution2(const int*values, int rows, int cols)
{
if (values == nullptr || rows <= 0 || cols <= 0)
return 0;
int*maxValues = new int[rows];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
int left = 0;
int up = 0;
if (i > 0)
up = maxValues[j];
if (j > 0)
left = maxValues[j - 1];
maxValues[j] = max(up, left) + values[i*cols + j];
}
}
int maxValue = maxValues[cols - 1];
delete maxValues;
return maxValue;
}