题目原址
https://leetcode.com/problems/unique-paths/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.
Example1:
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
Example2:
Input: m = 7, n = 3
Output: 28
解题思路
利用动态规划的思想,动态规划的关键是找到递推公式。该题:到达某一个点的路径数等于到达它上一点的陆静姝与它左边的路径数之和。即:起始点到终点(i,j)
的路径数 = 起始点到(i - 1,j)
的路径数 + 起始点到(i,j - 1)
的路径数。
AC代码
class Solution {
public int uniquePaths(int m, int n) {
int[][] ret = new int[m][n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(i == 0 || j == 0) ret[i][j] = 1;
else
ret[i][j] = ret[i - 1][j] + ret[i][j - 1];
}
}
return ret[m - 1][n - 1];
}
}