GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — [LeetCode] 62. Unique Paths · Issue #62 · grandyang/leetcode Open Description
There is a robot on an Given the two integers The test cases are generated so that the answer will be less than or equal to Example 1: Example 2: Constraints:
这道题让求所有不同的路径的个数,一开始还真把博主难住了,因为之前好像没有遇到过这类的问题,所以感觉好像有种无从下手的感觉。在网上找攻略之后才恍然大悟,原来这跟之前那道 Climbing Stairs 很类似,那道题是说可以每次能爬一格或两格,问到达顶部的所有不同爬法的个数。而这道题是每次可以向下走或者向右走,求到达最右下角的所有不同走法的个数。那么跟爬梯子问题一样,需要用动态规划 Dynamic Programming 来解,可以维护一个二维数组 dp,其中 dp[i][j] 表示到当前位置不同的走法的个数,由于每个位置只可能是由其上面或者右边过来,则当前的路径总数实际上就是从上面过来的路径总数加上右边过来的路径总数之和,然后可以得到状态转移方程为: dp[i][j] = dp[i - 1][j] + dp[i][j - 1],参见代码如下: 解法一: 这里为了节省空间,这里也可以使用一维数组 dp,一行一行的刷新也可以,代码如下: 解法二: 这道题其实还有另一种很数学的解法,参见网友 Code Ganker 的博客,实际相当于机器人总共走了 m + n - 2步,其中 m - 1 步向下走,n - 1 步向右走,那么总共不同的方法个数就相当于在步数里面 m - 1 和 n - 1 中较小的那个数的取法,实际上是一道组合数的问题,在初中时,我们就应该学过组合数的计算方法,就比如在n个数字中取k个数字的方法,就是 解法三: Github 同步地址: 类似题目: Minimum Path Cost in a Grid Minimum Cost Homecoming of a Robot in a Grid Number of Ways to Reach a Position After Exactly k Steps Paths in Matrix Whose Sum Is Divisible by K 参考资料: https://leetcode.com/problems/unique-paths/ https://leetcode.com/problems/unique-paths/discuss/22981/My-AC-solution-using-formula LeetCode All in One 题目讲解汇总(持续更新中...) (欢迎加入博主的知识星球,博主将及时答疑解惑,并分享刷题经验与总结,快快加入吧~) 微信打赏 Venmo 打赏 Activity
MetadataMetadataAssigneesLabelsNo labels TypeProjectsMilestoneRelationshipsDevelopmentIssue actions |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |