【LeetCode】【动态规划】表格移动问题
前言
这里总结了两道表格移动的问题,分别是:Unique Paths 和
题一:Unique Paths
描述
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3 Output: 28
思路:动态规划
因为只能向右或者向下移动,所以
dp[0][j] = 1
dp[i][0] = 1
dp[i][j] = dp[i -1][j] + dp[i][j-1]
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int> > dp(m ,vector<int>(n,1)); for(int i = 1;i<m;++i){ for(int j=1;j<n;++j){ dp[i][j] = dp[i -1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } };
题二:Minimum Path Sum
描述
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
思路
这个是表格的变形,这是将线路上的权值相加,求最小值,所以dp数组更新的是线路上最小的权值和:递推公式如下:
dp[0][0] = grid[0][0]
dp[i][0] = dp[i - 1][0] + grid[i][0]
dp[0][j] = dp[0][j-1] + grid[0][j]
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
class Solution { public: int minPathSum(vector<vector<int>>& grid) { if(grid.size() == 0) return 0; int n = grid.size(), m = grid[0].size(); cout<<m<<" "<<n<<endl; vector<vector<int> > dp(n, vector<int>(m, 0)); for(int i = 0;i<n;++i){ for(int j=0;j<m;++j){ if(i == 0 && j == 0) dp[i][j] = grid[i][j]; else if(i == 0 && j != 0) dp[i][j] = dp[i][j-1] + grid[i][j]; else if(j == 0 && i != 0) dp[i][j] = dp[i-1][j] + grid[i][j]; else dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; } } return dp[n-1][m-1]; } };
或者将for循环里的 if else提取出来分别处理:
class Solution { public: int minPathSum(vector<vector<int>>& grid) { if(grid.size() == 0) return 0; int n = grid.size(), m = grid[0].size(); cout<<m<<" "<<n<<endl; vector<vector<int> > dp(n, vector<int>(m, 0)); dp[0][0] = grid[0][0]; for(int i = 1;i<n;++i) dp[i][0] = dp[i - 1][0] + grid[i][0]; for(int j = 1;j<m;++j) dp[0][j] = dp[0][j-1] + grid[0][j]; for(int i = 1;i<n;++i){ for(int j= 1;j<m;++j){ dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; } } return dp[n-1][m-1]; } };
心有猛虎,细嗅蔷薇 转载请注明:https://www.cnblogs.com/ygh1229/