[Leetcode] 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?

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。

哦哦,刚刚学习到,原来这个玩意儿叫滚动数组,也叫状态压缩。(๑•̀ㅂ•́)و✧!

上一篇写了很久的全英文博客居然被吞了,册那!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值