【LeetCode】#62不同路径(Unique Paths)
题目描述
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
问总共有多少条不同的路径?
说明:m 和 n 的值均不超过 100。
示例
示例 1:
输入: m = 3, n = 2
输出: 3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
- 向右 -> 向右 -> 向下
- 向右 -> 向下 -> 向右
- 向下 -> 向右 -> 向右
示例 2:
输入: m = 7, n = 3
输出: 28
Description
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
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:
- Right -> Right -> Down
- Right -> Down -> Right
- Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
解法
class Solution {
public int uniquePaths(int m, int n) {
int[][] road = new int[n][m];
road[0][0] = 1;
for(int i=1; i<n; i++){
road[i][0] = 1;
}
for(int j=1; j<m; j++){
road[0][j] = 1;
}
for(int i=1; i<n; i++){
for(int j=1; j<m; j++){
road[i][j] = road[i-1][j] + road[i][j-1];
}
}
return road[n-1][m-1];
}
}