算法: 唯一路径62. Unique Paths
Posted 架构师易筋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 唯一路径62. Unique Paths相关的知识,希望对你有一定的参考价值。
# 62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
How many possible unique paths are there?
Example 1:
Input: m = 3, n = 7
Output: 28
Example 2:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Example 3:
Input: m = 3, n = 3
Output: 6
Constraints:
- 1 <= m, n <= 100
It’s guaranteed that the answer will be less than or equal to 2 * 109.
1. 动态规划解法
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++) dp[i][0] = 1;
for (int i = 0; i < n; i++) dp[0][i] = 1;
for (int r = 1; r < m; r++) {
for (int c = 1; c < n; c++) {
dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
}
}
return dp[m - 1][n - 1];
}
}
2. 排列组合解法
这是一个组合问题,可以在没有 DP 的情况下解决。对于 mxn 网格,机器人必须准确地向下移动 m-1 步和向右移动 n-1 步,这些可以以任何顺序完成。
例如,给出的问题是 3x7 矩阵,机器人需要以任意顺序执行 2+6 = 8 步,其中 2 步向下,6 步向右。那不过是一个排列问题。向下表示为“D”,向右表示为“R”,以下是路径之一:-
DRRRDRRR
我们必须告诉上面给定单词的排列总数。因此,将 m & n 都减少 1 并应用以下公式:-
总排列 = (m+n)!/(m!* n!)
以下是我的代码做同样的事情:-
class Solution {
public int uniquePaths(int m, int n) {
if (m == 1 || n == 1) return 1;
m--;
n--;
int hi = m > n ? m : n;
int lo = m > n ? n : m;
long r = 1;
for (int i = 1, k = hi + 1; k <= hi + lo; i++, k++) {
r = r * k / i;
}
return (int)r;
}
}
参考
https://leetcode.com/problems/unique-paths/discuss/22953/Java-DP-solution-with-complexity-O(n*m)
https://leetcode.com/problems/unique-paths/discuss/22958/Math-solution-O(1)-space
以上是关于算法: 唯一路径62. Unique Paths的主要内容,如果未能解决你的问题,请参考以下文章
leetCode 62.Unique Paths (唯一路径) 解题思路和方法
LeetCode-面试算法经典-Java实现062-Unique Paths(唯一路径)
LeetCode第[62]题(Java):Unique Paths 及扩展
LeetCode-面试算法经典-Java实现063-Unique Paths II(唯一路径问题II)