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.
开始的时候的答案是这样,会超时的。
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]; } };
你看,这样需要m*n的空间,实际上,我们并不需要保持整个的m*n,只需要保证最外面的一行和一列就好了。
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]; } };
话说空间对时间有影响么。。。