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?
Constraints:
1 <= m, n <= 100
It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
Examples
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
解题思路
首先需要明确,这里的机器人行走方式只有两种,就是向右或者向下
这就意味着不用盘向下又回上去的情况,也就是说,对于一个3*3的图,可以分割为两个2*3的图,而不用考虑被割裂的两条1*3
那么按照这个思路,我首先想到的是递归
class Solution {
public int time(int m, int n){
if(m == 1 || n == 1)
return 1;
if(m == 2 && n == 2)
return 2;
int a, b;
a = time(m - 1, n);
b = time(m, n - 1);
return a + b;
}
public int uniquePaths(int m, int n) {
return time(m, n);
}
}
这套代码很好理解,就不加赘述了,但这种递归会爆栈
后来一想,这不就是个动态规划吗
行/列 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
---|---|---|---|---|---|---|---|
1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
2 | 1 | 1+1=2 | 2+1=3 | 1+3=4 | 1+4=5 | 1+5=6 | 1+6=7 |
3 | 1 | 1+2=3 | 3+3=6 | 4+6=10 | 10+5=15 | 15+6=21 | 21+7=28 |
4 | 1 | 1+3=4 | 4+6=10 | 10+10=20 | 20+15=35 | 21+35=56 | 28+56=84 |
那初始化就是
n
u
m
[
i
]
[
0
]
=
0
num[i][0] = 0
num[i][0]=0
n
u
m
[
0
]
[
i
]
=
0
num[0][i] = 0
num[0][i]=0
递归公式就是
n
u
m
[
i
]
[
j
]
=
n
u
m
[
i
−
1
]
[
j
]
+
n
u
m
[
i
]
[
j
−
1
]
num[i][j] = num[i-1][j] + num[i][j-1]
num[i][j]=num[i−1][j]+num[i][j−1]
代码
这里就放动态规划的了
class Solution {
public int uniquePaths(int m, int n) {
int[][] answer = new int[m][n];
int i, j;
for(i = 0; i < n; i++){
answer[0][i] = 1;
}
for(i = 0; i < m; i++){
answer[i][0] = 1;
}
for(i = 1; i < m; i++){
for(j = 1; j < n; j++){
answer[i][j] = answer[i - 1][j] + answer[i][j - 1];
}
}
return answer[m - 1][n - 1];
}
}