【LeetCode & 剑指offer刷题】动态规划与贪婪法题7:47:礼物的最大价值

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

47:礼物的最大价值

题目:

在一个m*n的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向左或者向下移动一格,直到到达棋盘的右下角。给定一个棋盘及其上面的礼物,请计算你最多能拿多少价值的礼物?

解答:

1. 利用循环的动态规划实现,使用辅助二维数组

定义f(i,j)表示到达坐标为(i,j)的格子时能拿到的礼物总和的最大值;
有两种路径到达(i,j):(i-1,j)或者(i,j-1);
f(i,j) = max(f(i-1,j), f(i,j-1)) + gift[i,j];
使用循环来计算避免重复子问题。
 
class Solution
{
public :
    int getMaxValue_solution ( 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 )
            maxValues [ i ] = new int [ cols ];
        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] = std::max(left, up) + 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 ;
    }
};

2. 优化空间复杂度,使用一维数组

题目中可知,坐标(i,j)的最大礼物价值仅仅取决于坐标为(i-1,j)和(i,j-1)两个格子;
因此第i-2行以上的最大价值没有必要保存下来。
使用一维数组保存:(0,0)…(0,j-1)保存的是(i,0)…(i,j-1)的最大价值;(0,j)…(0,cols-1)保存的是(i-1,j)…(i-1,cols-1)的最大价值。
每次计算新的(i,j)时,使用数组下标j-1和j的最大值加当前礼物值即可。
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
(i,j)
 
 
 
 
 
 
 
 
 
 
 
 
 
class Solution {
public :
    int getMaxValue_solution ( const int * values , int rows , int cols ) {
        if ( values == nullptr || rows <= 0 || cols <= 0 )
            return 0 ;
        int* maxValues = new int[cols]; //开辟一个一维数组即可,a[i][j]上的最大值存与maxValues[j]中
        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 ] = std :: max ( left , up ) + values [ i * cols + j ];
            }
        }
        int maxValue = maxValues[cols - 1];
        delete [] maxValues ;
        return maxValue ;
    }
};
 
 

猜你喜欢

转载自www.cnblogs.com/wikiwen/p/10229350.html