有什么问题或建议欢迎留言交流~
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?
Above is a 7 x 3 grid. 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
给定m*n的棋盘格,从左上角出发,只能向下或向右走,有几条路可以通向右下角
看到一种更快速的解法,贴上来分享一下
思路:m*n的棋盘,从左上角到右下角,需要经过(m-1)个向右和(n-1)个向下,总共需要走过(m+n-2)个格子,计算从(m+n-2)个格子中选(m-1)个向右的格子,有种组合,即等价于求有多少条路径。
Class Sulotion{
public int uniquePaths(int m, int n) {
double value = 1;
for (int i = 1; i <= n - 1; i++) {
value *= ((double) (m + i - 1) / (double) i);
}
return (int) Math.round(value);
}
}
最开始两种方法都出现了time limit exceeded超时问题ε(┬┬﹏┬┬)3,类似图的深度优先遍历的递归算法和广度优先遍历
深度优先遍历:能往右走就走一步,能往下走就走一步,走到右下角时,返回经过进入节点到达右下角的路径数,下面附上代码,看代码还是比较好理解的
class Solution {
public int uniquePaths(int m, int n) {
return repeat(m, n, 0, 0);
}
private int repeat(int m, int n, int right, int down){
if (m == right + 1 && n == down + 1)
return 1;
int count = 0;
if (right+1 < m)
count += repeat(m, n, right+1, down);
if (down + 1 < n)
count +=repeat(m, n, right, down+1);
return count;
}
}
广度优先遍历:先把左上角插入队列,当队列不空时循环以下操作,取队首,如果队首是右下角,则计数加1,如果不是右下角,则把该位置的右边和下边入队列。
import java.util.concurrent.LinkedBlockingQueue;
class Solution {
public int uniquePaths(int m, int n) {
if (m == 1 || n == 1)
return 1;
int count = 0;
Queue queue = new LinkedBlockingQueue<>();
int[] p = {0,0};
queue.add(p);
while (!queue.isEmpty()){
int[] cur = queue.remove();
if (cur[0] == m -1 && cur[1] == n - 1)
count++;
if (cur[0] < m - 1) {
int[] next = {cur[0]+1, cur[1]};
queue.add(next);
}
if (cur[1] < n - 1) {
int[] next = {cur[0], cur[1]+1};
queue.add(next);
}
}
return count;
}
}
最后一种方法,可以从左上角出发到达每个结点的路径,需要O(m*n)的空间来存放到达每个节点的路径。
动态规划:到达右下角,要么是到了右下角的上面一格,要么是到达右下角的左边一格,即到达右下角的路径数=到达右下角上面一格的路径数+到达右下角的左一格的路径数。
class Solution {
public int uniquePaths(int m, int n) {
int[][] path = new int[m][n];
path[0][0] = 1;
for (int i = 0; i < m; i++){
int j = 0;
if (i == 0)
j = 1;
for (; j < n; j++){
path[i][j] = ((i != 0)? path[i-1][j]:0) + ((j != 0)? path[i][j-1]:0);
}
}
return path[m-1][n-1];
}
}