首页 > 代码库 > LeetCode "Minimum Path Sum" - 2D DP
LeetCode "Minimum Path Sum" - 2D DP
An intuitive 2D DP: dp[i][j] = min(grid[i-1][j-1] + dp[i-1][j], grid[i-1][j-1] + dp[i][j+1])
class Solution {public: int minPathSum(vector<vector<int> > &grid) { // dp[i][j] = min(dp[i-1][j] + dp[i][j], dp[i][j-1] + dp[i][j]); int n = grid.size(); // ver if (n == 0) return 0; int m = grid[0].size();// hor if (m == 0) return 0; // Init vector<vector<unsigned long>> dp; dp.resize(n + 1); for (int i = 0; i < dp.size(); i++) dp[i].resize(m + 1); std::fill(dp[0].begin(), dp[0].end(), std::numeric_limits<int>::max()); for (int i = 0; i <= n; i++) dp[i][0] = std::numeric_limits<int>::max(); dp[1][1] = grid[0][0]; for (int i = 1; i <= n; i ++) for (int j = 1; j <= m; j++) { if (i == 1 && j == 1) continue; dp[i][j] = std::min( grid[i - 1][j - 1] + dp[i - 1][j], grid[i - 1][j - 1] + dp[i][j - 1] ); } return dp[n][m]; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。