- 礼物的最大值,给定一个M*N的棋盘,每个棋盘里有一个标的价值的礼物,从左上角开始,每次只能向下或向右获得礼物,不能回走,直到右下角输出,求最多能拿多少礼物
解法一:一般走路可以回溯法,但是该走的路必须走完,否则不知道最大值,用递归遍历所有路径
解法二:动态规划,找最优子结构,申请一临时数组存储到点i最大的值,如果要输出路径可以顺带保存路径。优化空间,因为每个空间只与i-1行和j-1列格子有关,i-2行以上无关,可以用一个列向量保存i-1行的累计数据,遍历时更新即可,空间效率高
解法一:
int getMaxValue_solution3(const int* values, int rows, int cols, int currR,int currC)//recursive
{
if (currR >= rows || currC >= cols) return 0;
if (currR == rows - 1 && currC == cols - 1)
return values[currR*cols+currC];
int rightVal = getMaxValue_solution3(values, rows, cols, currR, currC + 1);
int downVal = getMaxValue_solution3(values, rows, cols, currR + 1, currC);
return std::max(values[currR*cols + currC] + rightVal, values[currR*cols + currC] + downVal);
}
int getMaxValue_solution3(const int* values, int rows, int cols)//recursive
{
if (values == nullptr || rows <= 0 || cols <= 0) return 0;
return getMaxValue_solution3(values, rows, cols, 0, 0);
}
解法二:
int getMaxValue_solution4(const int* values, int rows, int cols)//dynamic
{
if (values == nullptr || rows <= 0 || cols <= 0) return 0;
int* MaxValue = new int[rows*cols]();
MaxValue[0] = values[0];
if (rows > 1) MaxValue[cols] = values[0] + values[cols];
if (cols > 1) MaxValue[1] = values[0] + values[1];
for (int r = 0; r < rows;r++)
{
for (int c = 0; c < cols;c++)
{
if ((r == 0 && c == 0) || (r == 1 && c == 0) || (r == 0 && c == 1))
continue;
else if (r == 0 && c != 0)
MaxValue[r*cols + c] = MaxValue[r*cols + c - 1] + values[r*cols + c];
else if (r != 0 && c == 0)
MaxValue[r*cols + c] = MaxValue[(r - 1)*cols + c] + values[r*cols + c];
else
MaxValue[r*cols + c] = std::max(MaxValue[(r-1)*cols+c]+values[r*cols+c], MaxValue[r*cols+c-1]+values[r*cols+c]);
}
}
int ret = MaxValue[rows*cols - 1];
delete[] MaxValue;
return ret;
}