leetcode 64. 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.



class Solution {
public:
	int minPathSum(vector<vector<int>>& grid) {
		if (grid.empty())
			return 0;
		if (grid[0].empty())
			return 0;
		if (grid[0].size() == 1)
		{
			int re = 0;
			for (int i = 0; i < grid.size(); i++)
				re += grid[i][0];
			return re;
		}
		if (grid.size() == 1)
		{
			int re = 0;
			for (int i = 0; i < grid[0].size(); i++)
				re += grid[0][i];
			return re;
		}
		vector<int>gridminsum(grid[0].size());
		gridminsum[0] = grid[0][0];
		for (int i = 1; i < grid[0].size(); i++)
			gridminsum[i] = grid[0][i]+gridminsum[i-1];
		for (int i = 1; i < grid.size(); i++)
		{
			gridminsum[0] += grid[i][0];
			for (int j = 1; j < grid[0].size(); j++)
				gridminsum[j] = gridminsum[j - 1] + grid[i][j] < gridminsum[j]
				+ grid[i][j] ? gridminsum[j - 1] + grid[i][j] : gridminsum[j] + grid[i][j];
		}
		vector<int>tt(grid[0].size());
		tt[grid[0].size() - 1] = 0;
		for (int i = grid[0].size() - 2; i >= 0; i--)
			tt[i] = tt[i + 1] + grid[grid.size() - 1][i + 1];
		int min = gridminsum[0] + tt[0];
		for (int i = 1; i < grid[0].size(); i++)
			if (gridminsum[i] + tt[i] < min)
				min = gridminsum[i] + tt[i];
		return min;
	}
};


accepted

你可能感兴趣的:(LeetCode)