welcome to my blog
LeetCode Top 100 Liked Questions 62. Unique Paths (Java版; Medium)
题目描述
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?
Note: m and n will be at most 100.
Example 1:
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 -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
第一次做, 动态规划, (i,j)的状态取决于(i-1, j)和(i,j-1)的状态
/*
动态规划: (i,j)被访问几次要看(i-1,j)和(i,j-1)
*/
class Solution {
public int uniquePaths(int m, int n) {
if(m<1||n<1)
return 0;
//
//n是行数, m是列数
int[][] res = new int[n][m];
res[0][0] = 1;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(i-1>=0)
res[i][j] += res[i-1][j];
if(j-1>=0)
res[i][j] += res[i][j-1];
}
}
return res[n-1][m-1];
}
}
第一次做, 回溯法, 和预想的一样, 超时了, 37 / 62 个通过测试用例
/*
尝试各种可能, 明显可以使用回溯法, 但估计会超时
需要改成动态规划
*/
class Solution {
public int uniquePaths(int m, int n) {
if(m<1||n<1)
return 0;
//
int res = Core(n, m, 0, 0);
return res;
}
//n是行数, m是列数
public int Core(int n, int m, int i, int j){
//base case
if(i==n-1 && j==m-1)
return 1;
if(i > n-1 || j > m-1)
return 0;
int choseRight = Core(n, m, i, j+1);
int choseDown = Core(n, m, i+1, j);
return choseRight + choseDown;
}
}
第一次做, 使用排列组合, 实用long计算会溢出; 58 / 62 个通过测试用例; 实用float计算,在转成int时小数有误差; float用的是科学计数法, 所以表示的数字比long大很多
class Solution {
public int uniquePaths(int m, int n) {
if(m<1||n<1)
return 0;
/*
不管是什么走法, 肯定是向右走n-1步, 向下走m-1步
所以一共走了n-1+m-1步, 从总步数中挑出n-1个位置向左右走,剩下的位置向左走, 一共有C_(n-1+m-1)^(n-1)种可能, 这就是最终的结果
*/
double small = (double)(n-1), big = (double)(n-1+m-1);
double res = 1;
for(double i=big; i>big - small; i--)
res = res * i;
for(double i=small; i>0; i--)
res /= i;
return (int)res;
}
}