您的位置:首页 > 产品设计 > UI/UE

[LeetCode] Algorithms-62. Unique Paths

2018-01-11 14:18 429 查看

描述:

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?



思路:

题意很简单,现在来看这道题也很简单,但是做的时候却花了挺多时间的,主要有以下问题:

1. 超时

刚拿到的时候就直接使用递归实现,简单明了,第一次自己写的代码如下,但是超时了。

class Solution {
public:
int uniquePaths(int m, int n) {
if(m == 0 || n == 0) return 0;
if(m == 1 || n == 1) return 1;

return uniquePaths(m -1, n) + uniquePaths(m, n - 1);
}
};


2. 组合

最开始看这道题的时候就发现是一道高中时候的组合数问题,走的总步数是m + n -2,其中横着走m - 1步,竖着走n - 1步,直接一个组合公式就好了,但是写好之后提交还是有问题:



分母为0?怎么可能啊是吧。都是几个整数相乘怎么会出现0,最后发现应该是阶乘越界的问题,阶乘的数字太大了,超过了表示的范围,就算把数据类型设为long long也还是越界,这个办法也不行

class Solution {
public:
int uniquePaths(int m, int n) {
if(m == 0 || n == 0) return 0;
if(m == 1 || n == 1) return 1;

long long mu = 1;
long long z = 1;

for(int i = 1; i <= m - 1; i++) {
mu *= i;
z *= m + n - 1 - i;
}

return z / mu;
}
};


3. 动态规划

最后查阅网上的办法,知道这是一道动态规划的问题,由于还没有学动态规划,就直接贴代码了,学了之后再来补

参考Code_Ganker的的博客:LeetCode || Unique Paths

class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> v(n, 1);
for(int i=1; i<m; ++i){
for(int j=1; j<n; ++j){
v[j]+=v[j-1];
}
}
return v[n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: