LeetCode Online Judge 题目C# 练习 - Minimum Path Sum
2012-09-29 03:32
369 查看
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.
递归:
DP:
代码分析:
经典的递归(Top-down),DP(Bottom-up)题。DP一般都比递归来的效率高,主要是每次function 调用都新创建一个stack,但是有些问题递归用的巧,也是让人为之一震!
Note: You can only move either down or right at any point in time.
递归:
public static int MinimumPathSum(List<List<int>> grid) { int m = grid.Count; int n = grid[0].Count; return MinimumPathSumRecursive(grid, m - 1, n - 1); } public static int MinimumPathSumRecursive(List<List<int>> grid, int x, int y) { if (x == 0 && y == 0) { return grid[0][0]; } else if (x == 0) { return MinimumPathSumRecursive(grid, 0, y - 1) + grid[0][y]; } else if (y == 0) { return MinimumPathSumRecursive(grid, x - 1, 0) + grid[x][0]; ; } else { return Math.Min(MinimumPathSumRecursive(grid, x - 1, y), MinimumPathSumRecursive(grid, x, y - 1)) + grid[x][y]; } }
DP:
public static int MinimumPathSumDP(List<List<int>> grid) { int m = grid.Count; int n = grid[0].Count; int[,] ret = new int[m, n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 && j == 0) { ret[i, j] = grid[0][0]; continue; } if (i == 0) { ret[i, j] = ret[i, j - 1] + grid[i][j]; continue; } if (j == 0) { ret[i, j] = ret[i - 1, j] + grid[i][j]; continue; } if (ret[i - 1, j] <= ret[i, j - 1]) { ret[i, j] = ret[i - 1, j] + grid[i][j]; continue; } else { ret[i, j] = ret[i, j - 1] + grid[i][j]; continue; } } } return ret[m - 1, n - 1]; }
代码分析:
经典的递归(Top-down),DP(Bottom-up)题。DP一般都比递归来的效率高,主要是每次function 调用都新创建一个stack,但是有些问题递归用的巧,也是让人为之一震!
相关文章推荐
- LeetCode Online Judge 题目C# 练习 - Combination Sum II
- LeetCode Online Judge 题目C# 练习 - Largest Rectangle in Histogram
- LeetCode Online Judge 题目C# 练习 - Letter Combinations of a Phone Number
- LeetCode Online Judge 题目C# 练习 - PermutationsII
- LeetCode Online Judge 题目C# 练习 - Trapping Rain Water
- LeetCode Online Judge 题目C# 练习 - Insert Interval
- LeetCode Online Judge 题目C# 练习 - Longest Common Prefix
- LeetCode Online Judge 题目C# 练习 - Minimum Window Substring
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array
- LeetCode Online Judge 题目C# 练习 - Integer to Roman
- LeetCode Online Judge 题目C# 练习 - Longest Palindromic Substring
- LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Roman to Integer
- LeetCode Online Judge 题目C# 练习 - Rotate Image
- LeetCode Online Judge 题目C# 练习 - Search in Rotated Sorted Array II
- LeetCode Online Judge 题目C# 练习 - Jump Game
- LeetCode Online Judge 题目C# 练习 - Remove Duplicates from Sorted List
- LeetCode Online Judge 题目C# 练习 - Balanced Binary Tree