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 any numbers along its path.
Note: You can only move either down or right at any point in time.
The answer at the beginning is this, it will time out.
Class Solution {public: int minpathsum (vector<vector<int>>& grid) { int m = grid. Size (); int n = grid[0].size (); int dp[m][n]; Dp[0][0] = grid[0][0]; for (int i = 1; i < m; ++i) dp[i][0] = dp[i-1][0] + grid[i][0]; for (int i = 1; i < n; ++i) dp[0][i] = dp[0][i-1] + grid[0][i]; for (int i = 1;i<m;++m) for (int j = 1; j<n;++n) dp[i][j] = min (dp[i-1][j],dp[i][j-1]) + grid[i][j]; return dp[m-1][n-1];} ;
You see, this requires m*n space, in fact, we do not need to maintain the entire m*n, just to ensure that the outermost row and a column is good.
Class Solution {public: int minpathsum (vector<vector<int>>& grid) { int m = grid. Size (); int n = grid[0].size (); int dp[m],hr[n]; Dp[0] = hr[0] = grid[0][0]; for (int i = 1; i < m; ++i) dp[i] = dp[i-1] + grid[i][0]; for (int i = 1; i < n; ++i) { hr[i] = hr[i-1] + grid[0][i]; } Update horizontal line every time for next use int tmp; for (int i = 1;i<m;++i) { hr[0] = dp[i]; for (int j=1;j<n;++j) { Hr[j] = min (hr[j-1],hr[j]) + grid[i][j]; } } return hr[n-1];} ;
Does space have an effect on time?
[LC] Minimum Path Sum