• [Leetcode 26] 62 Unique Paths


    Problem:

    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?

    Above is a 3 x 7 grid. How many possible unique paths are there?

    Note: m and n will be at most 100.

    Analysis:

    It is a simple DP problem. Assume Smn is the number of unique paths when the grid is m*n.

    Then Smn = S(m-1)n + Sm(n-1). If simply coding it, it will has Time Limit Exceeded error due to the many recomputations.

     S(23, 12) = S(22, 12) + S(23, 11)

           = S(21, 12) + S(22, 11) + S(22, 11) + S(23, 10)    // rep 1

            = S(20, 12) + S(21, 11) + S(21, 11) + S(22, 12) +S(21, 11) + S(22, 10) + S(22, 10) + S(23, 9)  //rep 3

            = ....

    The time complxity here may be expotential.

    So we need to use a bottom-up method which compute base cases first and store the result into the table for future reference.

    The time complexity is only O(m*n)

    Code:

     1 class Solution {
     2 public:
     3     int uniquePaths(int m, int n) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int tab[m][n];
     7         
     8         for (int i=0; i<m; i++) 
     9             for (int j=0; j<n; j++) {
    10                 if (i == 0 || j == 0)
    11                     tab[i][j] = 1;
    12                 else
    13                     tab[i][j] = -1;
    14             }
    15         
    16         for (int i=1; i<m; i++) {
    17             for (int j=1; j<n; j++) {
    18                 if (tab[i][j] == -1) 
    19                     tab[i][j] = tab[i-1][j] + tab[i][j-1];
    20             }
    21         }
    22         
    23         return tab[m-1][n-1];
    24     }
    25 };
    View Code

    Attention:

  • 相关阅读:
    多线程实现双色球
    使用google api material icons在网页中插入图标
    网页前端制作好的网站
    n元线性方程非负整数解的个数问题
    Dilworth定理证明
    一个简易的Python全站抓取系统
    gensim word2vec好的教程
    C语言一些常用的功能
    python3正则表达式
    python3创建目录
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086644.html
Copyright © 2020-2023  润新知