题目描述
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
问总共有多少条不同的路径?
示例 1:
输入: m = 3, n = 2
输出: 3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
- 向右 -> 向右 -> 向下
- 向右 -> 向下 -> 向右
- 向下 -> 向右 -> 向右
总结
SC:排列组合
SC2:动态规划, 第一个很好想到,但是后面的优化不容易想到,虽然原理都是一样的
EC用的dfs, 但是超时了
Sample Code
class Solution {
public int uniquePaths(int m, int n) {
int N = n + m - 2;
int K = n - 1 > m - 1 ? m - 1 : n - 1;
long res = 1;
for (int i = 1; i <= K; i++)
res = res * (N - K + i) / i;
return (int) res;
}
}
Sample Code 2
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for ( int i = 0 ; i < m ; i++ ) {
for ( int j = 0 ; j < n ; j++ ) {
if ( i == 0 || j == 0 )
dp[i][j] = 1;
else
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
return dp[m - 1][n - 1];
}
}
Sample Code 2-优化1
空间复杂度 O(2n)
class Solution {
public int uniquePaths(int m, int n) {
int[] pre = new int[n];
int[] cur = new int[n];
Arrays.fill(pre, 1);
Arrays.fill(cur,1);
for (int i = 1; i < m;i++){
for (int j = 1; j < n; j++){
cur[j] = cur[j-1] + pre[j];
}
pre = cur.clone();
}
return pre[n-1];
}
}
作者:powcai
链接:https://leetcode-cn.com/problems/two-sum/solution/dong-tai-gui-hua-by-powcai-2/
Sample Code 2-优化2
空间复杂度 O(n)
class Solution {
public int uniquePaths(int m, int n) {
int[] cur = new int[n];
Arrays.fill(cur,1);
for (int i = 1; i < m;i++){
for (int j = 1; j < n; j++){
cur[j] += cur[j-1] ;
}
}
return cur[n-1];
}
}
作者:powcai
链接:https://leetcode-cn.com/problems/two-sum/solution/dong-tai-gui-hua-by-powcai-2/
ERROR Code
class Solution {
private int res = 0;
public int uniquePaths(int m, int n) {
dfs(m, n, 0, 0);
return res;
}
private void dfs(int m, int n, int i, int j) {
if(i==m-1 && j==n-1) {
res++;
return;
}
if(i < m) dfs(m, n, i+1, j);
if(j < n) dfs(m, n, i, j+1);
}
}