Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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?
有个图来着,Markdown贴起来很麻烦.不贴了.
Above is a 3 x 7 grid. How many possible unique paths are there?

Note: \(m\) and \(n\) will be at most 100.

解题思路,没啥可说, 用 dynamic programming.
步骤:
step 1: 看 https://mp.weixin.qq.com/s/0AgJmQNYAKzVOyigXiKQhA, 动态规划入门最好材料,没有之一! 10分钟看完,然后第二步.
step 2: 画图自己做这个题.^^

主要是先建模型,既,分析出:

  1. 状态转移公式,本题有3个状态转移公式,分别对应这i,j条件.具体参考最下方的代码(简单递归,当然无法执行,因为时间复杂度为 \(O(2^n)\), 但能很好的展示了转移公式);
  2. 最优子结构(分别对应各自的状态转移公式);
  3. 边界,既F[0,0] = 1.

自己想法,自个代码^^:
\(O(m*n)\) time, \(O(n)\) extra space.

class Solution {
public:
    // 真正的DP求解
    // $O(m*n)$ time, $O(n)$ extra space.
    // 时间复杂度无法再小了,但空间复杂度还可以再小.
    // space complexity 最低可为 min(m, n);
    // 听说有 $O(1)$ 的空间复杂度?
    // 如果不用 DP, 可用 math 的方法,如下:
    // https://leetcode.com/problems/unique-paths/discuss/

    int uniquePaths(int m, int n) {
        if(m == 1 || n == 1) return 1;
        if(m < n) return uniquePaths(n, m);

        vector<int> temp(n - 1, 0);
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                if(i == 1 && j == 1) temp[0] = 2;
                else if(i == 1 && j > 1) temp[j - 1] = 1 + temp[j - 2];
                else if(i > 1 && j == 1) temp[0] = temp[0] + 1;
                else if(i > 1 && j > 1) temp[j - 1] = temp[j - 1] + temp[j - 2];
            }
        }
        return temp[n - 2];
    }
};

下面是简单递归,但 time complexity \(O(2^n)\), 太高了.
下面代码可清晰地展示出DP的三要素:
状态转移公式、最优子结构和边界.

class Solution {
public:
    // 方法一: 简单递归,但 time complexity $O(2^n)$, 太高了.
    int uniquePaths(int m, int n) {
        int i = m - 1, j = n - 1;
        if(i == 0 && j == 0) return 1;
        else if(i == 0 && j != 0) return uniquePaths(i, j - 1);
        else if(j == 0 && i != 0) return uniquePaths(i - 1, j);
        else if(j > 0 && i > 0) return uniquePaths(i, j - 1) + uniquePaths(i - 1, j);
    }
};
posted on 2017-08-31 17:25  英雄与侠义的化身  阅读(151)  评论(0编辑  收藏  举报