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]; } };