• [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:

  • 相关阅读:
    select poll使用
    linux下tomcat shutdown后 java进程依然存在
    poj 1222 EXTENDED LIGHTS OUT(高斯消元)
    poj 2377 Bad Cowtractors
    C#:总结页面传值几种方法
    从 Racket 入门函数式编程
    程序猿接私活经验总结,来自csdn论坛语录
    什么是SEO?SEO干嘛的?怎么做SEO?
    Java设计模式-观察者模式
    非常特别的一个动态规划新手教程
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086644.html
Copyright © 2020-2023  润新知