zoukankan      html  css  js  c++  java
  • [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:

  • 相关阅读:
    Eclipse workspace被锁定
    OpenWrt增加软件包
    多核cpu关闭、开启核心
    python基础-元组(tuple)及内置方法
    JS变量+作用域
    JS宣传页项目-综合实战
    JS实现轮播图特效(带二级导航)
    JS DOM属性+JS事件
    JS DOM操作(创建、遍历、获取、操作、删除节点)
    JS中BOM操作知识点
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086644.html
Copyright © 2011-2022 走看看