Unique Path
来源:互联网 发布:端口号 传输层 编辑:程序博客网 时间:2024/06/06 08:44
Unique Path是一道递归或者说动态规划的基本题
下面用c语言实现
#include <stdio.h>#include <malloc.h>#include <memory.h>int uniquePathsR(int m, int n) {if(m < 1 || n < 1) return 0;if(m == 1 || n == 1) return 1;return uniquePathsR(m - 1, n) + uniquePathsR(m, n -1);}int uniquePathsRM2(int m, int n, int *mem, int columns){if(m < 1 || n < 1) return 0;if(m == 1 || n == 1) return 1;if(mem[m * columns + n] > 0) return mem[m * columns + n];mem[m * columns + n] = uniquePathsRM2(m - 1, n, mem, columns) + uniquePathsRM2(m, n - 1, mem, columns);return mem[m * columns + n];}int uniquePathsRM(int m, int n){int *mem = (int *)malloc((m + 1) * (n + 1) * sizeof(int));memset(mem, -1, (m + 1) * (n + 1) * sizeof(int));int numOfPaths = uniquePathsRM2(m, n, mem, n);free(mem);mem = NULL;return numOfPaths;}int uniquePathsDP(int m, int n){int dp[m][n]; //变长数组,c99新特性 memset(dp, 0, sizeof(dp));for(int i = 0; i < m; i++)dp[i][0] = 1;for(int j = 0; j < n; j++)dp[0][j] = 1;for(int i = 1; i < m; i++)for(int j = 1; j < n; j++)dp[i][j] = dp[i - 1][j] + dp[i][j - 1];return dp[m - 1][n - 1];}int uniquePathsDPS(int m, int n){int dp[n];for(int i = 0; i < n; i++) dp[i] = 1;for(int i = 1; i < m; i++)for(int j = 1; j < n; j++)dp[j] = dp[j] + dp[j - 1];return dp[n - 1];}int main(){printf("%d\n",uniquePathsR(3,4));printf("%d\n",uniquePathsRM(3,4));printf("%d\n",uniquePathsDP(3,4));printf("%d\n",uniquePathsDPS(3,4));return 0;}
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">用c++实现</span>
#include <iostream>#include <vector>using namespace std;int uniquePathsDP(int m, int n){vector<vector<int> > dp(m, vector<int>(n, 1));for(int i = 1; i < m; i++)for(int j = 1; j < n; j++)dp[i][j] = dp[i - 1][j] + dp[i][j - 1];return dp[m - 1][n - 1];}int uniquePathsDPS(int m, int n){vector<int> dp(n, 1);for(int i = 1; i < m; i++)for(int j = 1; j < n; j++)dp[j] = dp[j] + dp[j - 1];return dp[n - 1];}int main(){cout << uniquePathsDP(3,4) << endl;cout << uniquePathsDPS(3,4) << endl;return 0;}
直接用自顶向下的递归会超时:
Time Limit Exceeded:Last executed input:23, 12
记忆化搜索的数组用全局数组时会比较好写,如果不用全局数组则需要传递数组指针作为参数。记忆化搜索两步:取、存。
滚动数组可以优化空间。
0 0
- Unique path
- Unique Path
- Unique Path
- Unique Path
- unique-path
- Unique Path II
- LeetCode 61. Unique Path
- [Leetcode]Unique Path
- [Leetcode]Unique Path II
- 10.3 Unique Path II
- Unique Path 2 - leetcode
- [leetcode] Unique Path II
- 【LeetCode】Unique Path Ⅱ
- Unique Path--LeetCode
- Unique Path II--LeetCode
- Unique path ii
- Unique Path II
- [Leetcode]Unique Path II
- LinuxC多线程编程第五篇:线程通信(Condition)
- Python函数式编程指南(四):生成器
- python学习1:字符串的使用
- 解决office 2013在win 8.1 输入法超级慢
- POJ 1062:昂贵的聘礼:简单的dij最短路变形
- Unique Path
- STM32 定时器中断
- 数学之美系列二十一:布隆过滤器(Bloom Filter)
- 一个引起service为空的原因
- UISearchbar中自定义 放大镜图标 placeolder字体颜色 文本框背景色 兼容ios7
- 数据库创建表问题
- .NET Framework 版本和依赖关系
- Oracle 块修改跟踪 (Block Change Tracking) 说明
- 洗牌算法