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?
public class Solution {
public int uniquePaths(int m, int n) {
if (m > n) {
int temp = m;
m = n;
n = temp;
}
if (m <= 1) return m; // Corner cases, one border is 0 or 1.
// Uses a map to memoize previous results:
// The map is filled of 1, so that first step is already done.
int[] map = new int[n];
int t = 0;
while( t < n){
map[t] = 1;
t++;
}
// For every horizontal step...
for (int i = 1; i < m; ++i) {
// For every vertical step...
for (int j = 1; j < n; ++j) {
map[j] += map[j - 1];
}
}
// The last element contains our solution.
return map[n - 1];
}
}
本来我是非常直接简单的想到了DFS,不要问我为什么对DFS有这样大的执念。最后发现应该是个简单的DP问题。
DP问题和recursive的区别?
主要区别在于子问题的重复。
维基百科上最简单的例子就是斐波那契数列。比如F5 = F4+F3, F4 = F3+F2,这里F3被重复计算了两次,每次都需要F3再call自己的function执行计算。从时间复杂度上来看,是非常不划算的。
DP的解决方案也很简单粗暴,那就是把子问题的解全部记录下来。只计算一遍,需要用的时候直接从map里拿(这里的map也只是需要一个一位数组)。
本题按理来说,应该是用一个二维数组来记录子问题的解.
P[m][n] = P[m-1][n] + P[m][n-1]
这里m出现了两次,虽然他们所属的列数不同,但是因为这个robot只是向有行走的,没有回头路。所以n-1, n 可以认为是从时间上看到的先后两个点。
P[m] = P[m] + P[m-1]
也就是说等号两边的P[m] 代表的是时间上前后,空间上左右相邻的两个解。
还有一点很重要的是:
要把该一位数组初始化为全1。
哦哦,刚刚学习到,原来这个玩意儿叫滚动数组,也叫状态压缩。(๑•̀ㅂ•́)و✧!
上一篇写了很久的全英文博客居然被吞了,册那!