[LeetCode]62. Unique Paths
2016-12-12 17:21
337 查看
https://leetcode.com/problems/unique-paths/
naive做法是经典DP,很直观。
naive解法:
排列组合解法:
C(total, down),从总步数里面选down步向下的,属于组合问题,每一步down都是一样的
优化DP解法:
用到的DP只有下方元素和右侧元素,其实可以合并到一个数组里面。在遍历该数组的时候,是从下往上的,下方是代表之前的下方元素,上方代表之前未优化的右侧元素。空间复杂度O(min(m, n))这里面有一个trick如下注释。
naive做法是经典DP,很直观。
naive解法:
public class Solution { public int uniquePaths(int m, int n) { if (m < 1 || n < 1) { return 0; } int[][] dp = new int[m] ; for (int i = 0; i < m; i++) { dp[i][n - 1] = 1; } for (int i = 0; i < n; i++) { dp[m - 1][i] = 1; } for (int i = m - 2; i >= 0; i--) { for (int j = n - 2; j >= 0; j--) { dp[i][j] = dp[i + 1][j] + dp[i][j + 1]; } } return dp[0][0]; } }
排列组合解法:
C(total, down),从总步数里面选down步向下的,属于组合问题,每一步down都是一样的
public class Solution { public int uniquePaths(int m, int n) { long res = 1; // 总步数 int total = m + n - 2; // 要向下走的步数 int down = n - 1; for (int i = 1; i <= down; i++) { res = res * (total - down + i) / i; } return (int) res; } }
优化DP解法:
用到的DP只有下方元素和右侧元素,其实可以合并到一个数组里面。在遍历该数组的时候,是从下往上的,下方是代表之前的下方元素,上方代表之前未优化的右侧元素。空间复杂度O(min(m, n))这里面有一个trick如下注释。
public class Solution { public int uniquePaths(int m, int n) { if (m < n) { // So trick. return uniquePaths(n, m); } int[] dp = new int ; Arrays.fill(dp, 1); for (int j = m - 2; j >= 0; j--) { for (int i = n - 2; i >= 0; i--) { dp[i] += dp[i + 1]; } } return dp[0]; } }
相关文章推荐
- [LeetCode] 62. Unique Paths (DP问题)
- leetcode 62. Unique Paths (dp)
- [LeetCode] Algorithms-62. Unique Paths
- [leetcode] 62. Unique Paths
- leetcode 62. Unique Paths
- leetcode解题报告:62. Unique Paths
- LeetCode --- 62. Unique Paths
- LeetCode 62. Unique Paths
- LeetCode 62. Unique Paths
- leetcode-62. Unique Paths
- Leetcode 62. Unique Paths
- Leetcode 62. Unique Paths
- leetcode_middle_48_62. Unique Paths
- leetCode刷题归纳-Dynamic Programming(62. Unique Paths)
- [LeetCode] 62. Unique Paths
- Leetcode 62. Unique Paths (Medium) (cpp)
- leetcode.array--62. Unique Paths
- Leetcode:62. Unique Paths
- LeetCode 62. Unique Paths(所有不同的路径)
- [LeetCode]62. Unique Paths