64.最小路径和

(1)第一种方法,递归暴力解决。 

class Solution {
public:
	int dfs(vector>& grid, int i, int j){
		if (i == grid.size() || j == grid[0].size()){
			return INT_MAX;    //超出范围的时候,返回一个最大值,一开始写成了if (i == grid.size() || j == grid.size())
		}
		if (i == grid.size() - 1 && j == grid[0].size()-1){
			return grid[i][j];   //递归终止条件
		}
		return grid[i][j] + min(dfs(grid, i + 1, j), dfs(grid, i, j+1));
	}
	int minPathSum(vector>& grid) {
		return dfs(grid, 0, 0);
	}
};


int main(){
	vector> grid = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } };
	Solution solution;
	int res = solution.minPathSum(grid);
	return 0;
}

(2)递归+二维数组记忆搜索

class Solution {
public:
	int DFS(vector>& grid, int i, int j, vector>& memo){
		if (i == grid.size() || j == grid[0].size()) return INT_MAX;
		if (i == grid.size() - 1 && j == grid[0].size() - 1) return grid[i][j];
		if (memo[i][j] == -1) memo[i][j] = grid[i][j] + min(DFS(grid, i + 1, j, memo), DFS(grid, i, j + 1, memo));
		return memo[i][j];
	}
	int minPathSum(vector>& grid) {
		int m = grid.size();
		int n = grid[0].size();
		vector> memo = vector>(m, vector(n, -1));
		return DFS(grid, 0, 0, memo);
	}
};

int main(){
	vector> grid = { { 1, 3, 1 }, { 1, 5, 1 }, { 4, 2, 1 } };
	Solution solution;
	int res = solution.minPathSum(grid);
	return 0;
}

(3)用一维数组做记忆搜索似乎不能用递归,只能用动态规划。

错误1

class Solution {
public:

	int minPathSum(vector>& grid) {
		vectordp = vector(grid[0].size(), 0);
		for (int i = grid.size() - 1; i >= 0; i--){
			for (int j = grid[0].size()-1; j >= 0; j--){
				if (i == grid.size() - 1 && j != grid[0].size() - 1)
					dp[j]= grid[i][j] + dp[j + 1];
				if (i != grid.size() - 1 && j == grid[0].size() - 1)
					dp[j] = grid[i][j] + dp[j];
				if (i != grid.size() - 1 && j != grid[0].size() - 1)
					dp[j] =grid[i][j] + min(dp[j], dp[j + 1]);
				else
					dp[j] = grid[i][j];//右下角起始元素    //错误之处,if else,这行用个else是上个if只要不满足就执行这条语句
				                                           //而我们的意思是上边那几个if都不满足的情况下才执行这条语句。
			}
		}
		return dp[0];
	}
};

改正确

class Solution {
public:

	int minPathSum(vector>& grid) {
		vectordp = vector(grid[0].size(), 0);
		for (int i = grid.size() - 1; i >= 0; i--){
			for (int j = grid[0].size()-1; j >= 0; j--){
				if (i == grid.size() - 1 && j != grid[0].size() - 1)
					dp[j]= grid[i][j] + dp[j + 1];
				else if (i != grid.size() - 1 && j == grid[0].size() - 1)
					dp[j] = grid[i][j] + dp[j];
				else if (i != grid.size() - 1 && j != grid[0].size() - 1)
					dp[j] = grid[i][j]+ min(dp[j], dp[j + 1]);
				else
					dp[j] = grid[i][j];//右下角起始元素    //错误之处,if else,这行用个else是上个if只要不满足就执行这条语句
				                                           //而我们的意思是上边那几个if都不满足的情况下
			}
		}
		return dp[0];
	}
};

 

你可能感兴趣的:(Leetcode刷题)