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
Analysis
TC: O(mn)
Ver.2
观察到f实际上只和当前行和上一行有关, 因此f可以只用一维数组来节省空间. f[j]在更新前表示当前行的前一行的第j列的结果, f[j] += f[j - 1]意味着上一行第j列结果和当前行第j-1列结果相加.
Last updated
Was this helpful?