Unique Paths
https://leetcode.com/problems/unique-paths/
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?
Thoughts
给定M*N的矩阵,
设Fi,j为从(0, 0)处往下或往右走到(i, j)处的unique path的数目. 求F(M-1, N-1).
观察到要到达(i, j)只有从(i - 1, j)和(i, j - 1)两条路,也就是说f[i][j] = f[i - i][j] + f[i][j - 1]
Code
class Solution {
public int uniquePaths(int m, int n) {
int[][] f = new int[m][n];
for (int i = 0; i < n; i++) {
f[0][i] = 1;
}
for (int i = 0; i < m; i++) {
f[i][0] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
f[i][j] = f[i - 1][j] + f[i][j - 1];
}
}
return f[m - 1][n - 1];
}
}
Analysis
TC: O(mn)
Ver.2
观察到f实际上只和当前行和上一行有关, 因此f可以只用一维数组来节省空间. f[j]在更新前表示当前行的前一行的第j列的结果, f[j] += f[j - 1]意味着上一行第j列结果和当前行第j-1列结果相加.
class Solution {
public int uniquePaths(int m, int n) {
int[] f = new int[n];
f[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
f[j] += j > 0 ? f[j - 1] : 0;
}
}
return f[n - 1];
}
}
Last updated
Was this helpful?