`

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?

   LeetCode中的变形题目:Minimum Path Sum , Unique Paths II(障碍物)

 

   题目意思 : m x n 矩阵 ,从 00 到 (m-1)(n-1)有多少种走法

   思路 : 可以先假设3x3的矩阵,用树形图画出对应的可能路线图,00 = 01+10  , 01 = 02 + 11 , 02 = 12 =22 ,11 = 12 + 21 ,12 = 22 ,21 =22

   所以 , 可以知道这个问题的子问题就是 矩阵中 matrix[i][j]到终点的路线。

   得到递推式 :

   

W(R , D) = W(R + 1 , D) + W(R , D+1) D,R < m - 1 , n -1;
W(R , D) = W(R + 1 , D) D = n - 1
W(R , D) = W(R , D +  1) R = m - 1
 

 

public class Solution {
    public int uniquePaths(int m, int n) {
        int[][] matrix = new int[m][n]; // 存放每一个点到终点的路线
        for (int i = m - 1 ; i >= 0 ; i--) {
            for (int j = n - 1 ; j >= 0 ; j--) {
                if ( i == m - 1 && j == n - 1)
                    matrix[i][j] = 1;
                else if (j < n - 1 && i < m - 1 )
                    matrix[i][j] = matrix[i + 1][j] + matrix[i][j + 1];
                else if (j == n - 1)
                    matrix[i][j] = matrix[i + 1][j];
                else 
                    matrix[i][j] = matrix[i][j + 1];
            }
        }
        return matrix[0][0];
    }
}

 DISCUSS 中排列组合方法 :

    总共  m - 1次 down ,n - 1 right  所以 C(n - 1 + m - 1 , m - 1); 得到了下面的:

 public int uniquePaths(int m, int n) {
   if( m == 1 || n ==1) return 1;
   long count = 1;
   if(m>n){
       for(int i=1; i<=n-1; i++){
           count *= (m + i - 1);
           count /= i;
       }
   }else{
       for(int i=1; i<=m-1; i++){
           count *= (n + i - 1);
           count /= i;
       }
   }
   return (int)count;
}

 

第二种类型 : 表格中添加障碍物 值为1的不能通过 :

  思路: 很简单,只要在第一种的动态规划解法中,添加一些判断条件就可以了

 

public class Solution {
    // 添加了障碍物 1的格不能通过 
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        if(obstacleGrid[m-1][n-1] == 1 || obstacleGrid[0][0] == 1) return 0;
        int[][] matrix = new int[m][n];
        for (int i = m - 1 ; i >= 0 ; i--) {
            for (int j = n - 1 ; j >= 0 ; j--) {
                if(obstacleGrid[i][j] == 1) matrix[i][j] = 0; // 多了这句话
                else if ( i == m - 1 && j == n - 1)
                    matrix[i][j] = 1;
                else if (j < n - 1 && i < m - 1 )
                    matrix[i][j] = matrix[i + 1][j] + matrix[i][j + 1]; //注意这里你不要判断右边或下面的是否为1,因为它们的值反正0 , 没关系的 
                else if (j == n - 1)
                    matrix[i][j] = matrix[i + 1][j];
                else 
                    matrix[i][j] = matrix[i][j + 1];
            }
        }
        return matrix[0][0];
    }
}

 

分享到:
评论

相关推荐

    pcw0118#ZXBlog#LeetCode-62.Unique Paths(不同的路径数量)(简单dp)1

    1、记忆化 2、二维dp 3、滚动优化

    cpp-算法精粹

    Unique Paths II N-Queens N-Queens II Restore IP Addresses Combination Sum Combination Sum II Combination Sum III Generate Parentheses Sudoku Solver Word Search 总结 分治法 Pow(x,n) Sqrt(x) 贪心法 Jump...

    leetcode分类-LeetCode:力码

    Unique Paths Unique Paths II Longest Palindromic Substring Interleaving String Triangle Distinct Subsequences Decode Ways Palindrome Partitioning II Maximal Rectangle ###Recursion N-Queens N-Queens II...

    gasstationleetcode-leetcode:LeetcodeOJ解决方案

    62.Unique Paths, 63.Unique Paths II, 64.Minimum Path Sum 2017/03/09 70.Climbing Stairs, 198.House Robber, 55.Jump Game 72.Edit Distance, 97.Interleaving String, 115.Distinct Subsequences 2017/04/24 ...

    leetcode答案-leetcode:leetcode

    Unique Paths 应该是简单的数学排列组合问题,提炼一下其实就一句话:有m个黑球,n个白球,有多少种不同的排列方式。 我数学太差,没找到答案,直接上了动态规划。 Unique Paths II mod之后,可能数学公式就不能简单...

    UplusWithLeetCode:LGUPLUS开发人员litcode研究即兴(x)意愿(o)

    每周最后一个问题是hard挑战,只有那些想尝试的人。 第一周的问题 :hundred_points: 问题 关联 876.链表中间 1491....第2周的问题 :red_apple: 问题 ...1769.将所有球移动到每个盒子的... Unique Paths III难度:(困难)

    扩展矩阵leetcode-Leetcode:LeetcodeAnswer-Java

    扩展矩阵leetcode ...uniquePaths 63.不同路径II uniquePathsWithObstacles 139.单词拆分 wordBreak 279.完全平方数 numSquares 排序 56.合并区间 merge 75.颜色分类 sortColors 179.最大数 largestNumber 324.摆

    leetcode算法题主函数如何写-visual-your-algo:网站暂停升级中

    uniquePaths = function(m, n) { let dp = new Array(m).fill(0).map(() =&gt; new Array(n)); // dp[r][c] represents the number of possible paths from row = 0, col = 0 to row = r, col = c for (let row = 0; ...

    leetcode正方体堆叠-TakeUforward-SDE_180:TakeUforward-SDE_180

    leetcode正方体收藏TakeUforward-...Unique Paths Reverse Pairs (Leetcode) 从 GFG 中通过拼图(自行搜索) Day4: (Hashing) 2 Sum 问题 4 Sum 问题 Longest Consecutive Sequence Longest Subarray with 0 sum 给定

    lrucacheleetcode-LeetcodeSolution:Leetcode刷题的分类和答案记录

    63.Unique Paths II 64.最小路径和 70.爬楼梯 72.编辑距离 122. 买卖股票的最佳时机 II 152.最大积子阵列 198.强盗 322.硬币变化 贪心算法 45.跳跃游戏II 55.跳跃游戏 哈希 1.二和 3.最长不重复字符的子串 49.组字谜...

    leetcode叫数-Leetcode_JS:leetcode编程题,javascript版本

    Unique Paths 这道题是一道动态规划的题,还算简单。状态转移方程为: path[i][j] = path[i-1][j] + path[i][j-1]; i和j表示的是i*j的网格从左上角到右下角的路径数量。 并且初始的时候path[i][j]都为1。 为方便起见...

    leetcode530-Leetcode:新的开始

    leetcode 530 力码 全部的: 易(173/237+x) 中(144/437+x) 硬(4/x) 问题 1.Two Sum(dict) 7.(跳过)(数学) 9.(跳过)(串串技巧) 11.盛水最多的容器 ...47/46....54/59....63/62.Unique Paths 2 64.最小路径和

    leetcode棋盘-Algorithms:通用算法实现

    unique_paths.py(类似于 chess_board.c!)+ unique_paths2.py chess_board.c 效率测试 bin_search.py 素数.py 零知识.py Leetcode:现在很多小方案都是leetcode,我主要是为了好玩。 著名算法:Knuth-Morris-Pratt...

    RDF-based signature algorithms for computing differences of IFC models

    and present the Short Paths Crossings Algorithm (SPCA) that computes sets of paths with limited length from anonymous nodes taking into account their crossings. Empirical tests show that SPCA produces...

    KafkaOffsetMonitor监控工具2017年1月发布的版本

    Stopped polluting consumer groups in zookeeper by not creating a unique consumer group name for the consumer-offset and log-end-offset listener at each client instantiation. Improved ...

    cspell-action:GitHub行动针对存储库部署cspell

    unique 可选仅对一次拼写错误发出警告。 默认情况下,为false 。 产出 没有任何。 用法示例 uses : zwaldowski/cspell-action@v1 with : paths : " **/*.{md,js} " config : .github/workflows/cspell.json ...

    Imagining the Tenth Dimension:A New Way of Thinking About Time and Space

    Part scientific exploration, part philosophy, this unique book touches upon such diverse topics as dark matter, Feynman's "sum over paths", the quantum observer, and the soul. It is aimed at anyone ...

    leetcode1477-coding-for-fun:编码乐趣

    62.unique-paths.cpp [TODO] 5. 最长回文子串.cpp 第 3 天: [TODO] 96.unique-binary-search-trees.cpp [TODO] 70. 爬楼梯.cpp [TODO] 746. min-cost-climbing-stairs.cpp 第 4 天: [待办事项] leetcode/1143。 ...

    Network Security Technologies, Second Edition

    &lt;br&gt;http://www.auerbach-publications.com/home.asp&lt;br&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;Product Description&lt;br&gt;Network security development and implementation efforts involve the integration of technologies from seemingly unrelated fields that did not previously have to cross paths or internetwork. Areas such as cryptography, network protocols, and switch and router technology each have established theories and practices; developing expertise in ...

    cleanX:用于清理Xrays大型数据集的Python库

    cleanX 用于清理Xrays大型数据集的Python库。 (该库将于4/14/2021作为Python库发布。) 主要作者:医学博士Candace Makeda H. Moore其他作者:Oleg Sivokon... uniqueID (str): string name of column with image ID

Global site tag (gtag.js) - Google Analytics