To prove safety Offer - maximum value of 47. The gift of interview questions (dynamic programming)

1. Topic

In each cell have put a m * n board has a gift, each gift has a certain value (value greater than 0). You can start from the top left corner of the board to take the gift of the grid, and each time to the right or down to move one space, until reaching the lower right corner of the board. Given a chessboard and the value of the gift above, calculate how much you can get the most valuable gift?

示例 1:
输入: 
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
输出: 12
解释: 路径 13521 可以拿到最多价值的礼物
 
提示:
0 < grid.length <= 200
0 < grid[0].length <= 200

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

2. Problem Solving

Simple DP Title: Referring to the example in Bowen

  • First row, first column, there is no choice but to be a road came
  • The rest, can come from above and to the left, take the greatest
  • d p [ i ] [ j ] = g r i d [ i ] [ j ] + m a x ( d p [ i ] [ j 1 ] , d p [ i 1 ] [ j ] ) dp[i][j] = grid[i][j] + max(dp[i][j-1], dp[i-1][j])
class Solution {
public:
    int maxValue(vector<vector<int>>& grid) {
    	if(grid.empty() || grid[0].empty())
    		return 0;
    	int m = grid.size(), n = grid[0].size(), i, j;
    	vector<vector<int>> dp(m, vector<int>(n,0));
    	dp[0][0] = grid[0][0];
    	for(j = 1; j < n; j++)
    		dp[0][j] = dp[0][j-1] + grid[0][j];
    	for(i = 1; i < m; ++i)
    		dp[i][0] = dp[i-1][0] + grid[i][0];
    	for(i = 1; i < m; ++i)
    		for(j = 1; j < n; j++)
    			dp[i][j] = grid[i][j] + max(dp[i][j-1], dp[i-1][j]);
		return dp[m-1][n-1];
    }
};

Here Insert Picture Description

Published 701 original articles · won praise 652 · Views 200,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104711602