2013.12.21 02:43
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.
Solution:
It's obviously a dynamic programming problem, with the recurrence relations expressed as: a[x][y] = a[x - 1][y] + a[x][y - 1], a[0][0] = 1;
Using this formula will give you a solution in O(m * n) time. If you think one step further, you'll see this is the Pascal Triangle, thus each term in the triangle can be calculated with combinatorials, namely C(m + n - 2, m - 1).
To travel from (0, 0) to (m - 1, n - 1), you'll have to move (m - 1) steps down and (n - 1) steps right. Then comes the question: in the (m + n - 2) moves you make, which of them are down and which of them are right. The number of ways to choose is the answer we're looking for.
Time complexity is O(m) or O(n) or O(min(m, n)), depending on how you write the code to calculate the combinatorial. Space compelxity is O(1).
Accepted code:
1 class Solution { 2 public: 3 int uniquePaths(int m, int n) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 if(m > n){ 7 return uniquePaths(n, m); 8 } 9 10 // 1WA here, integer overflow 11 long long int sum, res; 12 13 // 1WA here, m and n start from 0, not 1 14 --m; 15 --n; 16 sum = res = 1; 17 // 1CE here, int i is not declared 18 for(int i = 1; i <= m; ++i){ 19 sum *= i; 20 res *= (m + n + 1 - i); 21 if(res % sum == 0){ 22 res /= sum; 23 sum = 1; 24 } 25 } 26 27 return res; 28 } 29 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)