博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode:Unique Paths
阅读量:4539 次
发布时间:2019-06-08

本文共 1146 字,大约阅读时间需要 3 分钟。

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?

分析:这道题可以用动态规划解,f[i][j]表示从(0,0)到(i,j)的路径数,递推公式为f[i][j] = f[i-1][j] + f[i][j-1]。时间复杂度O(n^2),空间复杂度O(n^2)。代码如下:

class Solution {public:    int uniquePaths(int m, int n) {        int f[m][n];                for(int i = 0; i < n; i++)            f[0][i] = 1;        for(int i = 0; i < m; i++)            f[i][0] = 1;                for(int i = 1; i < m; i++)            for(int j = 1; j < n; j++)                f[i][j] = f[i][j-1] + f[i-1][j];                return f[m-1][n-1];    }};

 其实在用动态规划时,我们可以用一个滚动数组代替二维数组。代码如下:

class Solution {public:    int uniquePaths(int m, int n) {        vector
f(n,0); f[0] = 1; for(int i = 0; i < m; i++) for(int j = 1; j < n; j++) f[j] = f[j] + f[j-1]; return f[n-1]; }};

 

转载于:https://www.cnblogs.com/Kai-Xing/p/4222638.html

你可能感兴趣的文章
poj2420 A Star not a Tree? 模拟退火
查看>>
微信小程序--登录授权,一键获取用户微信手机号并登录
查看>>
[转载] C#面向对象设计模式纵横谈——13. Proxy代理模式
查看>>
JqueryEasyUI浅谈---视频教程公布
查看>>
ASP.NET导出Excel,打开时提示“您尝试打开文件'XXX.xls'的格式与文件扩展名指定文件不一致”...
查看>>
Javaweb之 servlet 开发详解1
查看>>
Restore IP Addresses
查看>>
DWR框架简单应用
查看>>
KMP 学习心得-----转
查看>>
time.strftime:格式化字符串中含中文报错处理
查看>>
模态窗口缓存无法清除怎么办? 在地址上加个随机数吧"&rd=" + new Date().getTime()
查看>>
阿里的weex框架到底是什么
查看>>
Tesis enDYNA
查看>>
FxZ,C#开发职位面试测试题(30分钟内必须完成)
查看>>
[HNOI2007]分裂游戏
查看>>
Pandas基本介绍
查看>>
当拖动滚动条时 出现小图标
查看>>
LeetCode "Shortest Word Distance II"
查看>>
绕过阿里云防火墙继续扫描探测和SQL注入
查看>>
ln 软链接与硬链接
查看>>