【LeetCode】Unique Paths
2014-04-17 11:29
309 查看
参考链接
http://www.cnblogs.com/remlostime/archive/2012/11/15/2772263.html题目描述
Unique Paths
Total Accepted: 9698 TotalSubmissions: 31863My Submissions
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.
题目分析
动态规划开一个f[m]
的数组,f[i][j] = f[i-1][j] + f[i][j-1],空间时间复杂度O(m*n)。用滚动数组空间复杂度可降为O(n)
代码示例
/* 编译环境CFree 5.0 博客地址:http://blog.csdn.net/Snowwolf_Yang */ #include #include using namespace std; #if 0//超时 class Solution { public: int uniquePaths(int m, int n) { int sum = 0; uniquePathsCore(m,n,0,0,sum); return sum; } void uniquePathsCore(int m, int n, int i, int j, int &sum) { if(i == m-1 && j == n-1) { sum++; //printf("(%d,%d) ",i,j); //printf("end\n"); return; } if(j > f(m, vector(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-1][j] + f[i][j-1]; return f[m-1][n-1]; } }; #endif void test0() { Solution so; if(so.uniquePaths(1,1) != 1) printf("------------------------failed\n"); else printf("------------------------passed\n"); if(so.uniquePaths(1,2) != 1) printf("------------------------failed\n"); else printf("------------------------passed\n"); if(so.uniquePaths(1,3) != 1) printf("------------------------failed\n"); else printf("------------------------passed\n"); if(so.uniquePaths(2,1) != 1) printf("------------------------failed\n"); else printf("------------------------passed\n"); if(so.uniquePaths(2,2) != 2) printf("------------------------failed\n"); else printf("------------------------passed\n"); int out = so.uniquePaths(23,12) ; if(out != 193536720) printf("------------------------failed %d \n",out); else printf("------------------------passed\n"); } int main(int argc, char *argv[]) { test0(); return 0; }
推荐学习C++的资料
C++标准函数库http://download.csdn.net/detail/chinasnowwolf/7108919
在线C++API查询
http://www.cplusplus.com/
vector使用方法
http://www.cplusplus.com/reference/vector/vector/
相关文章推荐
- leetcode -- Unique Paths
- 【LeetCode】 062. Unique Paths
- leetcode62 Unique Paths
- [leetcode]Unique Paths
- 【Leetcode】Unique Paths (DP)
- 【LeetCode-面试算法经典-Java实现】【062-Unique Paths(唯一路径)】
- Leetcode62 Unique Paths
- leetcode-Unique Paths
- Leetcode Unique Paths
- LeetCode-62-Unique Paths
- LeetCode 62 Unique Paths 解题报告
- LeetCode Unique Paths
- leetcode---62. Unique Paths
- Leetcode 62: Unique Paths
- [leetcode]Unique Paths
- [LeetCode] Unique Paths-动态规划
- leetcode - Unique Paths
- leetcode(62). Unique Paths
- LeetCode: Unique Paths
- Leetcode-Unique Paths(dp)