《leetCode》:Unique Paths
来源:互联网 发布:mac桌面文件不能拖动 编辑:程序博客网 时间:2024/05/29 17:52
题目
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?Note: m and n will be at most 100.
思路一
思路:用递归来求解即可
一个点的路径总数等于右边节点的路径总数+正下方节点的路径总数
实现代码如下:
int uniquePaths(int m, int n) { if(m==1&&n==1){ return 0; } if(m==1||n==1){ return 1; } return uniquePaths(m,n-1)+uniquePaths(m-1,n); }
报超时错误,截图如下:
我在自己电脑的编译环境试了下,虽然在我的电脑上能够得到正确结果,但是我观察了下确实运行的时间过长。
测试代码如下:
int main(void){ int m,n; while(scanf("%d%d",&m,&n)!=EOF){ int result=uniquePaths(m,n); printf("%d \n",result); } return 0;}
出现这样的原因在于:递归深度过大。因此我们需要寻找更好的方法。
思路二:用空间来换取时间
借助空间来换取时间;
开辟一个m*n的数组空间,用来存储每个点到终点的可达路径的总数;
计算方法为:一个点的路径总数等于右边节点的路径总数+正下方节点的路径总数
int uniquePaths(int m, int n) { if(m<1||n<1){ return 0; } if(m==1||n==1){ return 1; } //开辟一段空间来保存结果 int **result=(int **)malloc(m*sizeof(int *)); if(result==NULL){ exit(EXIT_FAILURE); } for(int i=0;i<m;i++){ result[i]=(int *)malloc(n*sizeof(int)); if(result[i]==NULL){ exit(EXIT_FAILURE); } } result[m-1][n-1]=0; //最后一列为 1; for(int i=0;i<m;i++){ result[i][n-1]=1; } //最后一行为 1; for(int i=0;i<n;i++){ result[m-1][i]=1; } for(int i=m-2;i>=0;i--){ for(int j=n-2;j>=0;j--){ result[i][j]=result[i+1][j]+result[i][j+1]; } } return result[0][0];}
最后AC结果如下:
0 0
- leetcode Unique Paths && Unique Paths
- Leetcode-Unique Paths&Unique PathsII
- [LeetCode] Unique Paths and Unique Paths II
- leetcode--Unique Paths && Unique Paths ii
- leetcode--Unique Paths && Unique Paths ii
- 【Leetcode】【python】Unique Paths/Unique Paths II
- LeetCode: Unique Paths
- LeetCode: Unique Paths II
- [Leetcode] Unique Paths
- [Leetcode] Unique Paths II
- LeetCode : Unique Paths
- LeetCode : Unique Paths II
- leetcode 9: Unique Paths
- [LeetCode] Unique Paths
- [LeetCode] Unique Paths II
- [LeetCode]Unique Paths
- [LeetCode]Unique Paths II
- [LeetCode] Unique Paths
- JSP分页
- 数据结构上机实验--有向图邻接表的建立,深度广度搜索及拓扑排序
- 作百度地图定位时,location.getAddrStr()获取到的值一直为空的问题
- 链表的归并排序
- HH的一万天
- 《leetCode》:Unique Paths
- 漫谈以太网交换机
- Html CSS
- Coursera Course: Programming Languages
- 从PDF中提取信息----PDFMiner
- Auction
- c++输入
- JSP防盗链接
- POJ 2255Tree Recovery 二叉树重建(根据前序遍历和中序遍历写出后序遍历)