声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com
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?
Brief
机器人从起点走到终点,每次只能向下或者向右走,有多少条路径?
Input
(1)m=3,n=2
(2)m=7,n=3
Output
(1)3
(2)28
Explanation
m and n will be at most 100.
Ideas
二维动态规划问题。
机器人到达[i,j]这个位置有两种方法:
从[i-1,j]位置到达
从[i,j-1]位置到达
所以很容易写出状态转移方程:
d
p
[
i
]
[
j
]
=
d
p
[
i
−
1
]
[
j
]
+
d
p
[
i
]
[
j
−
1
]
dp[i][j]=dp[i-1][j]+dp[i][j-1]
dp[i][j]=dp[i−1][j]+dp[i][j−1]
Code
class Solution {
public int uniquePaths(int m, int n) {
if(m <= 0||m > 100||n <= 0||n > 100){
return 0;
}
int[][] dp = new int[m][n];
for(int i = 0; i < m; i ++){
dp[i][0] = 1;
}
for(int j = 0; j < n; j ++){
dp[0][j] = 1;
}
for(int i = 1;i < m; i ++){
for(int j = 1; j < n;j++){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
}
声明:本题及相关刷题笔记同步github之中,欢迎Fork & Star GitHub:https://github.com/HoqiheChen。如有不足之处,烦请改正。QQ Mail:851774342@qq.com