`

Algorithm之Unique Path

阅读更多
经典排列组合与动态规划题

一、原题:


    // https://leetcode.com/problems/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?
    
    
    +---+---+---+---+---+---+---+---+
    |ROB|   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+
    |   |   |   |   |   |   |   |   |
    +---+---+---+---+---+---+---+---+
    |   |   |   |   |   |   |   |end|
    +---+---+---+---+---+---+---+---+
    
    
    */
    



解法一
    /*
    
    // https://discuss.leetcode.com/topic/5623
    // java-dp-solution-with-complexity-o-n-m
    
    The assumptions are:

        - When (n==0||m==0) the function always returns 1 since the robot
          can't go left or up.
    
        - For all other cells. The result = uniquePaths(m-1,n) + uniquePaths(m,n-1)
    
    Therefore I populated the edges with 1 first and use DP to get the full 2-D array.
    
    */
    
    /*
        
        +----+----+----+----+----+----+----+----+
        | 1  | 1  | 1  | 1  | 1  | 1  | 1  | 1  |
        +----+----+----+----+----+----+----+----+
        | 1  | 2  | 3  | 4  | 5  | 6  | 7  | 8  |
        +----+----+----+----+----+----+----+----+
        | 1  | 3  | 6  | 10 | 15 | 21 | 28 | 36 |
        +----+----+----+----+----+----+----+----+
        | 1  | 4  | 10 | 20 | 35 | 56 | 84 |120 |
        +----+----+----+----+----+----+----+----+
    
    */


    // Time complexity: O(n^2)

    public int uniquePaths(int m, int n) {
        int[][] map = new int[m][n];
        
        for(int i = 0; i < m; i++){
            map[i][0] = 1;
        }
        
        for(int j = 0; j < n; j++){
            map[0][j] = 1;
        }
        
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                map[i][j] = map[i-1][j] + map[i][j-1];
            }
        }
        
        return map[m-1][n-1]; // the finish star.
    }


解法二
    // Time complexity: O(n^2)

    public int uniquePaths(int m, int n) {
        int[]dp = new int[n];
        dp[0] = 1;
        for(int i = 0; i < m; i++)
            for(int j = 1; j < n; j++)
                dp[j] = dp[j] + dp[j-1];
        return dp[n-1]; // the finish star.
    }



解法三
   // Time complexity: O(n)
   /*
    https://discuss.leetcode.com/topic/52660
    // java-0ms-solution-with-explanations
    
    
    When we solve this problem, we should keep in mind that this is a 
    permutation and combination problem of high school level. 
    Therefore, we need not to use DP solution or recursive solution.
    
    Given m and n, there will be m+n-2 steps. 
    Among these m+n-2 steps, n-1 steps are towards right and m-1 steps are towards down.
    
    the question is changed to: Select m-1 steps from m+n-2 steps.
    So, there will be (m-1)C(m+n-2) solutions, which is the same as (n-1)C(m+n-2). 
    
    All we need is to write a program quickly calculating (m-1)C(m+n-2) or (n-1)C(m+n-2).
*/    
    
    public int uniquePaths(int m, int n) {
         long result = 1;
         int steps = m + n - 2;

         for(int i=0; i < Math.min(m-1,n-1); i++)
             result = result * (steps - i) / (i + 1); 
             
         return (int)result;
    }


/*
    注意: 

    result = result * (steps - i) / (i + 1);

    不要写成

    result *= (steps - i) / (i + 1);
   
    的形式,否则后者在做除法时丢位导致结果错误。


*/




解法四

    // Time complexity: O(n)
    /*
    
    https://discuss.leetcode.com/topic/52660
    // java-0ms-solution-with-explanations
    
    https://discuss.leetcode.com/topic/31724
    // java-solution-0ms-4lines
    
    
    When we solve this problem, we should keep in mind that this is a 
    permutation and combination problem of high school level. 
    Therefore, we need not to use DP solution or recursive solution.
    
    Given m and n, there will be m+n-2 steps. 
    Among these m+n-2 steps, n-1 steps are towards right and m-1 steps are towards down.
    
    the question is converted to: Select m-1 steps from m+n-2 steps.
    So, there will be (m-1)C(m+n-2) solutions, which is the same as (n-1)C(m+n-2). 
    
    All we need is to write a program quickly calculating (m-1)C(m+n-2) or (n-1)C(m+n-2).
    

    
    */

  /*
    
    基础知识:(从 n 个数中 取出 m 个数)
    
    排列公式: result = n!/(n-m)!
    组合公式: result = n!/(n-m)!/m!
    
  ------------------------------------------------------  
    
    该题是一个组合题:
    
        7, 3
        
        steps = 8
        
        n = 3
        
        result = 8!/(3!*(8-3)!)
        
        8 7 6   5 4 3 2
        - - - * - - - -  
        3 2 1   5 4 3 2
        
 
     */
    public int uniquePaths(int m, int n) {
        int steps = m + n - 2;
        int min = Math.min(m - 1, n - 1);

        long sum = 1, sub = 1;        
        for(int i = 0; i < min; i++){
            sum *= (steps - i);
            sub *= (min - i);
        }

        return (int)(sum/sub);
   }

/*
   注意:这种解法乘完再除,相乘的结果可能会造成溢位,而出错。
         所以只适合数比较小的情况。

*/







二、增加些难度
/*
https://leetcode.com/problems/unique-paths-ii

Follow up for "Unique Paths":

Now consider if some obstacles are added to the grids. 
How many unique paths would there be?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.

[
  [0,0,0],
  [0,1,0],
  [0,0,0]
]
The total number of unique paths is 2.

Note: m and n will be at most 100.
*/


public int uniquePathsWithObstacles(int[][] obstacleGrid) {
    int width = obstacleGrid[0].length;
    int[] dp = new int[width];
    dp[0] = 1;
    for (int[] row : obstacleGrid) {
        for (int j = 0; j < width; j++) {
            if (row[j] == 1)
                dp[j] = 0;
            else if (j > 0)
                dp[j] += dp[j - 1];
        }
    }
    return dp[width - 1];
}











-


分享到:
评论

相关推荐

    A Neural Algorithm of Artistic Style(一个艺术风格化的神经网络算法)

    In fine art, especially painting, humans havemastered the skill to create unique visual experiences through composing a complex interplay between the con- tent and style of an image. Thus far the ...

    A line-search rectilinear path finding algorithm among simulated intelligent

    本文提出的算法的关键特性是引入了一个分布式知识库(Distributed Knowledge Base, DKB),该知识库与障碍物的互联段关联,并为这些段赋予唯一的标识号(Unique Identity Number, UIN)。这种方法使得算法能够有效地...

    官网下载:Windows-KB841290-x86-ENU.zip

    Fciv 2.0: xml as unique storage. Added -both option. Fciv 2.01: Exit with error code to allow detections of problem in a script. Fciv 2.02: Improved perfs. When both alg are specified, it's now done ...

    Introduction to Algorithms Lecture Notes (MIT 6.006)

    This module covers various shortest path algorithms, including Dijkstra's algorithm. 6. **Dynamic Programming: Stock Market** - **Motivation**: Uses dynamic programming to analyze stock market ...

    boost-caffe依赖库.rar

    标题中的"boost-caffe依赖库.rar"表明这是一个与Caffe深度学习框架相关的压缩包,其中包含了Caffe运行...例如,在Linux上,可能需要设置`LD_LIBRARY_PATH`环境变量,而在Windows上,则可能需要修改系统的PATH环境变量。

    linux-mycat 配置

    export PATH=$PATH:$MYCAT_HOME/bin ``` 保存并关闭文件,然后使更改生效: ```bash source ~/.bashrc ``` 现在,我们可以启动Mycat。进入Mycat的bin目录,执行: ```bash cd $MYCAT_HOME/bin ./mycat start ```...

    C++ 标准库 中文 高清 (2020最新带书签)

    首先,标准库中的`&lt;algorithm&gt;`头文件包含了各种通用的算法,例如排序(sort)、查找(find)、拷贝(copy)等,这些算法适用于不同的容器,如vector、list、set等。`&lt;allocators&gt;`头文件则涉及到内存分配策略,如...

    Algorithmic Game Theory Lecture Notes (Cornell CS6840)

    Consider a graph with two strategies: Strategy 1 represents the bottom path, while Strategy 2 represents the top path. Each edge has a delay function \(d(e)\) that is monotone increasing, meaning the ...

    DAOS技术手册.docx

    3. RAFT:Raft is a consensus algorithm used to distribute state transitions among DAOS server nodes,用于提供高可靠性和可用性的分布式系统解决方案。 4. ULT:User Level Thread,用于提供高效的线程管理。 ...

    boost_1_59_0.tar.gz mysql安装所需包.zip

    1. **智能指针**:如`shared_ptr`、`unique_ptr`和`weak_ptr`,它们提供了更安全的内存管理方式,避免了传统指针可能导致的悬挂指针和内存泄漏问题。 2. **算法**:包括各种容器操作的通用算法,如排序、查找、迭代...

    Boost视频教程

    下面将围绕“Boost深入剖析之使用技巧视频教程”这一主题进行详细的解析,包括Boost库的基本介绍、主要功能模块及其应用技巧等方面。 ### Boost库简介 Boost库是一个免费的、同行评审的、跨平台的C++源代码库,它...

    3、动态规划必练题(含解法).pdf

    可以使用Kadane's algorithm,动态规划思路是维护当前子数组的和`curr_sum`和全局最大和`max_sum`。 6. **Maximum Product Subarray** (最大乘积子数组) 类似于最大子数组和,但需要考虑负数的影响,可以同时维护...

    python3.6.5参考手册 chm

    PEP 519: Adding a file system path protocol PEP 495: Local Time Disambiguation PEP 529: Change Windows filesystem encoding to UTF-8 PEP 528: Change Windows console encoding to UTF-8 PEP 520: ...

    LeetcodeSolutions:我收集的评论很好的leetcode问题解决方案

    容器如vector、list、set、map等提供了便捷的数据存储和操作,而algorithm头文件中的函数如sort、find、unique等则简化了算法实现。此外,C++的模板机制允许编写泛型代码,增加了代码的复用性。 在解题过程中,我们...

    poj pku图论、网络流入门题总结、汇总

    - **算法选择:** Bellman-Ford 或 SPFA (Shortest Path Faster Algorithm)。 - **问题描述:** 寻找特定条件下的一组路径。 - **解题思路:** 通过Bellman-Ford或SPFA算法求解单源最短路径问题,并在此基础上通过...

    Codes

    《代码——LeetCode问题的解决之道》 代码,是编程世界的语言,是计算机与人类沟通的桥梁。在本文中,我们将深入探讨“Codes”这一主题,特别是与LeetCode平台相关的代码解决方案。LeetCode是一个广受欢迎的在线...

    LeetCode最全代码

    411 | [Minimum Unique Word Abbreviation](https://leetcode.com/problems/minimum-unique-word-abbreviation/) | [C++](./C++/minimum-unique-word-abbreviation.cpp) [Python](./Python/minimum-unique-word-...

    poj 图论 集合

    - **解法概述**:这是一道比较典型的最短路径问题,可以通过 Bellman-Ford 或 SPFA (Shortest Path Faster Algorithm) 来解决。 - **Bellman-Ford 算法**:适用于含有负权边的图的最短路径问题,能够检测负权重环。...

Global site tag (gtag.js) - Google Analytics